Ferdia O'Brien
Ferdia O'Brien

Reputation: 869

Does anyone have a good function for stripping out a specific shortcode in Wordpress?

I am in the process of setting up a new page template that displays a page's gallery (if it has one) in a single column, contained in an independent div, floated to the right, with all other content floated to the left. I can echo the gallery on the right via get_post_gallery(), and now I want to strip the gallery out of the_content().

What I essentially am hoping to locate is a function that does exactly the same thing as strip_shortcodes(), but for a specific shortcode. Something like strip_shortcode('gallery') or strip_shortcode('gallery', content()). Does anyone have such a function written up for Wordpress?

remove_shortcode('gallery') works bar it leaves the damn shortcode text itself behind when it runs. I can hide the gallery via CSS or remove it via jQuery but I'd rather it just not be output in the first place.

Upvotes: 3

Views: 538

Answers (1)

sven
sven

Reputation: 785

to remove a shortcode or a particular list of shortcode you can use this code.

global $remove_shortcode;
/**
* Strips and Removes shortcode if exists
* @global int $remove_shortcode
* @param type $shortcodes comma seprated string, array of shortcodes
* @return content || excerpt
*/
function dot1_strip_shortcode( $shortcodes ){
  global $remove_shortcode;
  if(empty($shortcodes)) return;

  if(!is_array($shortcodes)){
    $shortcodes = explode(',', $shortcodes);
  }
  foreach( $shortcodes as $shortcode ){
    $shortcode = trim($shortcode);
    if( shortcode_exists($shortcode) ){
        remove_shortcode($shortcode);
    }
    $remove_shortcode[$shortcode] = 1;
  }
  add_filter( 'the_excerpt', 'strip_shortcode' );
  add_filter( 'the_content', 'strip_shortcode' );    
}
function strip_shortcode( $content) {
  global $shortcode_tags, $remove_shortcode;

  $stack = $shortcode_tags;
  $shortcode_tags = $remove_shortcode;
  $content = strip_shortcodes($content);

  $shortcode_tags = $stack;
  return $content;
}
dot1_strip_shortcode( 'Test' );
dot1_strip_shortcode( 'Test, new_shortcode' );
dot1_strip_shortcode( array('Test', 'new_shortcode') );

Accepts single, comma seprated shortcode string or array of shortcodes.

Upvotes: 1

Related Questions