Skip to content

Instantly share code, notes, and snippets.

@taniarascia
Created June 7, 2016 00:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taniarascia/114c87ea17fa8af69d5408f16967f844 to your computer and use it in GitHub Desktop.
Save taniarascia/114c87ea17fa8af69d5408f16967f844 to your computer and use it in GitHub Desktop.
Escape HTML in WordPress
<?php
// Escape HTML in <code> or <pre><code> tags.
function escapeHTML($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 filterCode($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', 'filterCode', 9 );
add_filter( 'excerpt_save_pre', 'filterCode', 9 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment