Skip to content

Instantly share code, notes, and snippets.

@sc0ttkclark
Created September 21, 2021 01:54
Show Gist options
  • Save sc0ttkclark/c9cfa85a8ffb0a0cba0f704ed6eda379 to your computer and use it in GitHub Desktop.
Save sc0ttkclark/c9cfa85a8ffb0a0cba0f704ed6eda379 to your computer and use it in GitHub Desktop.
Do not run shortcodes for code/pre tags.
<?php
/**
* Do not run shortcodes for code/pre tags (at p7) before running the shortcodes (p8).
*
* @param string $post_content The post content.
*
* @return string The filtered post content.
*/
function do_not_run_shortcodes_for_code_tags( $post_content ) {
// Escape the shortcodes in <code> tags.
$post_content = preg_replace_callback( '/(<code[^>]*>)(.*?)(\[|\])(.*?)(<\/code>)/si', static function ( $match ) {
$start_tag = $match[1];
$content = $match[2] . $match[3] . $match[4];
$end_tag = $match[5];
$content = str_replace( [ '[', ']' ], [ '&#91;', '&#93;' ], $content );
return $start_tag . $content . $end_tag;
}, $post_content );
// Escape the shortcodes in <pre> tags.
$post_content = preg_replace_callback( '/(<pre[^>]*>)(.*?)(\[|\])(.*?)(<\/pre>)/si', static function ( $match ) {
$start_tag = $match[1];
$content = $match[2] . $match[3] . $match[4];
$end_tag = $match[5];
$content = str_replace( [ '[', ']' ], [ '&#91;', '&#93;' ], $content );
return $start_tag . $content . $end_tag;
}, $post_content );
return $post_content;
}
add_filter( 'the_content', 'do_not_run_shortcodes_for_code_tags', 7 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment