WordPress strip single shortcode from posts

I want to strip just the shortcodes in my blog posts. The only solution I found is a filter that I added to my functions.

function remove_gallery($content) {
  if ( is_single() ) {
    $content = strip_shortcodes( $content );
  }
  return $content;
}
add_filter('the_content', 'remove_gallery');

It removes all shortcodes including which I need for images. How can I specify a single shortcode to exclude or include?

Related posts

Leave a Reply

3 comments

  1. To remove only the gallery shortcode , register a callback function that returns an empty string:

    add_shortcode('gallery', '__return_false');
    

    But this will only work with the callbacks. To do it statically, you can temporarily change the global state of wordpress to fool it:

    /**
     * @param string $code name of the shortcode
     * @param string $content
     * @return string content with shortcode striped
     */
    function strip_shortcode($code, $content)
    {
        global $shortcode_tags;
    
        $stack = $shortcode_tags;
        $shortcode_tags = array($code => 1);
    
        $content = strip_shortcodes($content);
    
        $shortcode_tags = $stack;
        return $content;
    }
    

    Usage:

    $content = strip_shortcode('gallery', $content);
    
  2. For me, worked with:

    add_shortcode('shortcode_name', '__return_false');
    

    If i try to strip_shortcode, they are remove all shortocodes and changing the final result

  3. If you want to get only the content, excluding any shortcodes, try something like that

    global $post;
    $postContentStr = apply_filters('the_content', strip_shortcodes($post->post_content));
    echo $postContentStr;