Adding code to wordpress posts, especially if you, like me, use the HTML editor to write your posts, requires that you use HTML escape codes for changing every ‘>’ character into ‘>’ and so on and so forth as described in the wordpress codex.

Several solution are there including plugins that do more than just displaying the code but go beyond that towards formatting it as well. I have switched to using the google-code-prettify and therefore I needed a simple solution to just escape the HTML in <pre> HTML elements.

Therefore, I have put together the following piece of code that can be easily added to the template functions.php file to achieve that simple task.

function skinju_escape_pre ($content)
{
  $pieces = preg_split ( '/(<pre.*>.*?<\/pre>)/si', $content, -1, PREG_SPLIT_DELIM_CAPTURE );

  $procesed_content = '';
  foreach ($pieces as $piece)
  {
    if ( preg_match ( '/(?P<opening><pre.*>)(?P<content>.*)(?P<closing><\/pre>)/imxsU', $piece, $matches ))
    {
      $matches['content'] = str_replace ( '&', '&amp;', $matches['content']);
      $matches['content'] = str_replace ( '<', '&lt;', $matches['content']);
      $matches['content'] = str_replace ( '>', '&gt;', $matches['content']);
      $matches['content'] = str_replace ( '"', '&quot;', $matches['content']);
      $matches['content'] = str_replace ( '\'', '&#39;', $matches['content']);
      $procesed_content .=  $matches['opening']  . $matches['content'] .  $matches['closing'] ;
    }
    else
    {
      $procesed_content .= $piece;
    }
  }
  return ( $procesed_content );
}

add_filter('the_content', 'skinju_escape_pre', 10);