april-s
9/2/2014 - 5:31 PM

wp-remove-inactive-shortcodes.php

<?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;
  }