Skip to:
Content
Pages
Categories
Search
Top
Bottom

Re: How to show code in forum posts?


Boone Gorges
Keymaster

@boonebgorges

Here’s the code that does it on buddypress.org. It’s basically repurposed from bbPress.

I had to replace the actual backtick with the phrase `[backtick]` so that it would render properly on this forum. Make sure to correct that in your version.

`// Borrowed from bbPress
function bporg_encodeit( $matches ) {
$text = trim($matches[2]);
$text = htmlspecialchars($text, ENT_QUOTES);
$text = str_replace(array(“rn”, “r”), “n”, $text);
$text = preg_replace(“|nnn+|”, “nn”, $text);
$text = str_replace(‘&’, ‘&’, $text);
$text = str_replace(‘<', '<', $text);
$text = str_replace(‘>’, ‘>’, $text);
$text = “$text“;
if ( “[backtick]” != $matches[1] )
$text = “

$text

“;
return $text;
}

// Borrowed from bbPress
function bporg_decodeit( $matches ) {
$text = $matches[2];
$trans_table = array_flip(get_html_translation_table(HTML_ENTITIES));
$text = strtr($text, $trans_table);
$text = str_replace(‘
‘, ”, $text);
$text = str_replace(‘

‘, ”, $text);
$text = str_replace(‘

‘, ”, $text);
$text = str_replace(array(‘&’,’&’), ‘&’, $text);
$text = str_replace(”’, “‘”, $text);
if ( ‘

' == $matches[1] )
$text = "n$textn";
return "`$text`";
}

// Borrowed from bbPress. Makes code in backticks work, both in forum posts and in activity updates.
function bporg_code_trick( $text ) {
$text = str_replace(array("rn", "r"), "n", $text);
$text = preg_replace_callback("|(`)(.*?)`|", 'bporg_encodeit', $text);
$text = preg_replace_callback("!(^|n)`(.*?)`!s", 'bporg_encodeit', $text);
return $text;
}
add_filter( 'bp_get_the_topic_post_content', 'bporg_code_trick', 1 );
add_filter( 'bp_get_activity_content_body', 'bporg_code_trick', 1 );`
Skip to toolbar