April 7

Getting syntax highlighter to work on wordpress’s homepage (on some themes)

Posted by mtoledo
Filed under javascript | No Comments

Today I was trying to setup this blog with Syntax Highlighter Plus. Curiously, the syntax highlighting wouldn’t work on the home page where multiple posts are displayed, only when you clicked on a single post.

I’m adding this here because I couldn’t find anything about it anywhere except people suggesting to check the theme’s header and footer. But my problem was different.

Digging further, the code that does the actual highlighting is this:


function BBCodeToHTML( $content ) {

if ( !$this->CheckForBBCode( $content ) ) return $content;

$matches = $this->GetBBCode( $content );

if ( empty($matches) ) return $content; // No BBCode found, we can stop here

// Loop through each match and replace the BBCode with HTML
foreach ( (array) $matches as $match ) {
$language = $match[4] == '' ? $this->default_language : strtolower( $match[4] );
$content = str_replace( $match[0], '
<pre class="brush: ' . $language .">" . htmlspecialchars( $match[5], ENT_QUOTES ) . "</pre>
", $content );
$this->jsfiles2load[$language] = $this->languages[$language];
}

return $content;
}

I knew ‘CheckForBBCode’ was returning true, but the matches weren’t being replaced. Since they don’t use the same matcher for detecting source code, that would be expected on some of the times. But I wondered why was there any difference between the two texts at all..

Looking further in wordpress’s code, I found the following on includes/default-filter.php


add_filter('the_content', 'wptexturize');
add_filter('the_content', 'convert_smilies');
add_filter('the_content', 'convert_chars');
add_filter('the_content', 'wpautop');
add_filter('the_content', 'prepend_attachment');

add_filter('the_excerpt', 'wptexturize');
add_filter('the_excerpt', 'convert_smilies');
add_filter('the_excerpt', 'convert_chars');
add_filter('the_excerpt', 'wpautop');
add_filter('get_the_excerpt', 'wp_trim_excerpt');

Messing with the filter ‘wpautop’, I noticed that it affected both texts if I removed it from the ‘the_content’ hook, but only messed the home page one when I removed the ‘the_excerpt’ hook. So it would have to be that one of them was triggering the excerpt and the other wasn’t.

So, on my theme’s index.php, I found the following when displaying the posts on the homepage:

<div class="entry">

</div>

Compare to the one on the single post page:

<div class="entry">

</div>

So, I just updated my theme’s index to call ‘the_content()’ instead and syntax highlight was working again. That simple.

This entry was posted on Tuesday, April 7th, 2009 at 9:19 pm and is filed under javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply