Shortcodes are very powerfull tools in WordPress, at least they were because they are less popular since Gutenberg has arrived with WordPress 5.0.

I’m still using shortcodes in some rare cases (in one of my plugins for example) and when I need to write an article on how to use it, I want to be able to show example without executing it.

The above function allows to convert shortcodes braces in html characteres to prevent there execution when they are within the <code> or <pre> tags (the ones use to display code snippets). That mean the following [shortcode] will be converted to &#91;shortcode&#93; when your post HTML will be generated, but the browser will still display it as [shortcode].

function bweb_replace_shortcode($string) {
    $replace = array( '[' => '&#91;', ']' => '&#93;' );
    $newstring = str_replace( array_keys( $replace ), array_values( $replace ), $string[2] );
    return $string[1] . $newstring . $string[3];
}
function bweb_prevent_shortcode( $content ) {
	$pattern = '#(<pre.*?>|<code.*?>)(.*?)(<\/pre>|<\/code>)#imsu';
	return preg_replace_callback( $pattern, 'bweb_replace_shortcode', $content );
}
add_filter( 'the_content', 'bweb_prevent_shortcode', 9);

The function only affects the “display” of your content, it does not alter your content in database.

Post written byBrice CAPOBIANCO

WordPress addict and self-taught. I love to learn and to create, then to share…
Founder of bweb.
Share this post

Your email address will not be published. Required fields are marked *

Show 2 comments

2 comments

  1. Thanks, this is a real lifesaver. I’ve been pulling my hair out because of the GB Editor. I need to write documentation that include a lot of shortcodes to be explained.

    It’s way harder to find a solution and your little gem works a treat!