Skip to content

Instantly share code, notes, and snippets.

@zzap
Created September 30, 2016 18:21
Show Gist options
  • Save zzap/b919f63bf70862c985ae49fc00d16b3b to your computer and use it in GitHub Desktop.
Save zzap/b919f63bf70862c985ae49fc00d16b3b to your computer and use it in GitHub Desktop.
Strip shortcode tags for inactive shortcodes and leave content as is.
<?php
/**
* Hook
*/
add_filter( 'the_content', 'remove_inactive_shortcodes' );
/**
* Remove inactive shortcodes
*
* Make sure inactive shortcodes don't leave their junk in the content.
* We are striping their tags, leaving content as is. This function is attached to
* 'the_content' filter hook.
*
* @global $shortcode_tags Associative array of all active shortcodes.
* @link https://wordpress.org/support/topic/stripping-shortcodes-keeping-the-content/#post-2704758
*
* @param string $content Content to be filtered
* @return string Returns filtered content
*/
function remove_inactive_shortcodes( $content ) {
global $shortcode_tags;
$keys = array_keys( $shortcode_tags );
$exclude_codes = implode( '|', $keys );
$the_content = get_the_content();
// strip all shortcodes except $exclude_codes and keep all content
$the_content = preg_replace( "~(?:\[/?)(?!(?:$exclude_codes))[^/\]]+/?\]~s", '', $the_content );
$content = $the_content;
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment