If you write code on your blog, chances are that you use a syntax highlighter to make the code a bit easier to read. And if you’re on this page, then you likely use the SyntaxHighlighter Evolved plugin.

While this SyntaxHighlighter Evolved works amazing for syntax highlighting, I have noticed that when using this plugin with Jetpack’s infinite scroll, my code snippets weren’t getting highlighted after new posts were added. So, after living with it for the past year or so, I decided to fix the issue.

After doing a bit of searching, I found the following article on Jetpack.com: https://jetpack.com/support/infinite-scroll/#js-events

In that article, they mention how a `post-load JavaScript event is called after posts are fetched and rendered. So, if we combine that with the a call to highlight any code snippets we get this:

 * jQuery is likely already enqueued, but let's enqueue here
 * to make sure things don't explode.
add_action( 'wp_enqueue_scripts', 'moh_enqueue_jquery' );
function moh_enqueue_jquery() {
 wp_enqueue_script( 'jquery' );

 * This is where the magic happens.
add_action( 'wp_footer', 'moh_trigger_rehighlight', 101 );
function moh_trigger_rehighlight() {
    ( function( $ ) {
      $( document.body ).on( 'post-load', function () {
        if ( 'undefined' !== typeof SyntaxHighlighter ) {
      } );
    } )( jQuery );

If you take this example and throw it in a plugin or the functions.php file for your theme, then all SyntaxHighlighter code snippets should be highlighted every time infinite scroll retrieves a new page. :party:

Let’s stay in touch!

If you liked what you read, then consider filling out the form below and I'll send you an email any time I post about anything WordPress of Development related. You can even choose which lists you're interested in below!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.