WordPress Gallery Shortcode Pregreplace

Basically I need to remove the gallery shortcode from the WordPress content, I’m using

echo preg_replace('/]+]/', '',  get_the_content() );

It is removing the gallery shortcode successfully, but also the paragraph tags which I need to keep. The idea is that I want to output everything in the content except the gallery.

Related posts

Leave a Reply

2 comments

  1. You could use WordPress strip_shortcode function.

    Look at the example in the Codex.
    You can create a filter that strips shortcodes:

    function remove_shortcode_from($content) {
      $content = strip_shortcodes( $content );
      return $content;
    }
    

    and call it when you need (in your template):

    add_filter('the_content', 'remove_shortcode_from');
    the_content();
    remove_filter('the_content', 'remove_shortcode_from')
    

    EDIT 1

    Another way to get that (and answering you comment) you can use WordPress apply_filters function in the content after remove the undesirables shortcodes.

    //within loop
    $content = get_the_content();
    $content = preg_replace('/[gallery ids=[^]]+]/', '',  $content );
    $content = apply_filters('the_content', $content );
    echo $content;
    

    But I would not recommend to you to do that. I think forcing your site to modify the content of a post could make that hard to understanding. Maybe you should work with WordPress Excerpt and avoid any problem.

    A link that helped me

  2. 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( 'gallery' );
    

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