ControlledChaos
8/8/2016 - 3:19 PM

Escape HTML in posts for displaying code.

Escape HTML in posts for displaying code.

<?php

// Escape HTML in <code> or <pre><code> tags.
function ccd_escape_html( $arr ) {

    if ( version_compare(PHP_VERSION, '5.2.3' ) >= 0) {
        $output = htmlspecialchars($arr[2], ENT_NOQUOTES, get_bloginfo( 'charset' ), false);
    } else {
        $specialChars = array(
            '&' => '&amp;',
            '<' => '&lt;',
            '>' => '&gt;'
        );

        // decode already converted data
        $data = htmlspecialchars_decode( $arr[2] );
        // escapse all data inside <pre>
        $output = strtr( $data, $specialChars );
    }
    
    if ( ! empty( $output ) ) {
        return  $arr[1] . $output . $arr[3];
    } else {
        return  $arr[1] . $arr[2] . $arr[3];
    }
}

function ccd_filter_code( $data ) { 
    // Uncomment if you want to escape anything within a <pre> tag
    //$modifiedData = preg_replace_callback('@(<pre.*>)(.*)(<\/pre>)@isU', 'escapeHTML', $data);
    $modifiedData = preg_replace_callback( '@(<code.*>)(.*)(<\/code>)@isU', 'escapeHTML', $data );
    $modifiedData = preg_replace_callback( '@(<tt.*>)(.*)(<\/tt>)@isU', 'escapeHTML', $modifiedData );

    return $modifiedData;
}
add_filter( 'content_save_pre', 'ccd_filter_code', 9 );
add_filter( 'excerpt_save_pre', 'ccd_filter_code', 9 );

?>

Escape HTML in Posts

WordPress Snippet