Highlight Syntax Inline

If you still want to use SO-type backtick markup for styling your inline code examples, I’ve created some code that will accomplish it. To make it into your own plug-in, just add the code below to your functions.php. It calls the wordpress filter “the_content” to apply the transformation to the content when it is displayed, thereby keeping any transformations from becoming stored in the database.

function style_my_inline($content){

//what you use to denote your code
$inline_marker = "`";

//regex for code
$pattern = "https://wordpress.stackexchange.com/".$inline_marker."[\w\D\d]+?".$inline_marker."https://wordpress.stackexchange.com/";
preg_match_all($pattern,$content,$matches);

//what you want your surrounding markup to be 
$prepend_tag = "<span class = \"code\">";
$append_tag = "</span>";

//for each occurance in preg match results...
foreach($matches as $match){
    for($i=0;$i<count($match);$i++){
        //remove inline marker from match text
        $match_without_inline_marker = str_replace($inline_marker,'',$match[$i]);
        //add surrounding markup to match
        $match_with_tags = $prepend_tag.$match_without_inline_marker.$append_tag;
        //replace match in original content with marked-up match
        $content = str_replace($match[$i],$match_with_tags,$content);
    }
}

return $content;
}

apply_filters("the_content","style_my_inline");

Now, I tested the code above with some dummy text and used backticks to define code blocks like so:

Lorem ipsum dolor sit amet, `consectetur adipiscing elit`. Donec nec magna erat. `Aenean nisi ante`, semper vel imperdiet sed, laoreet.

Then applied the following css:

<style type = "text/css">
span.code{color:#56aaff;font-family:courier;background:#e5e5e5;padding:1px;}
</style>

And what I get looks like this:
screenshot of code block

Hope this works for you.

Leave a Comment