Skip to content

Instantly share code, notes, and snippets.

@aibrean
Last active August 29, 2015 14:05
Show Gist options
  • Save aibrean/21cc26636ed8be9b100e to your computer and use it in GitHub Desktop.
Save aibrean/21cc26636ed8be9b100e to your computer and use it in GitHub Desktop.
<?php
/**
* 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.
* [key] => value
* [shortcode_id] => shortcode_function
*
* @uses array_keys($array) Return all the keys or a subset of the keys of an array.
* @uses implode(string $glue , array $pieces) Returns a string containing a string representation of
* all the array elements in the same order, with the
* separator ($glue) string between each element.
* @uses preg_replace($pattern, $replacement, $string) Perform a regular expression search and replace.
*
* @link http://wordpress.org/support/topic/stripping-shortcodes-keeping-the-content#post-2977834
*
* @package WordPress
*/
add_filter( 'the_content', 'remove_inactive_shortcodes' );
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 but keep content
// $the_content = preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $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