Created
June 7, 2016 00:47
-
-
Save taniarascia/114c87ea17fa8af69d5408f16967f844 to your computer and use it in GitHub Desktop.
Escape HTML in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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( | |
'&' => '&', | |
'<' => '<', | |
'>' => '>' | |
); | |
// 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