Remove first instance of a shortcode from a post or page in WordPress

igor miske 177849

I came up with this snippet that allows you to filter the_content and remove the first instance of the [gallery] shortcode.

Why is this in any way useful, you’re thinking. I used it in Gallerize Pro to replace the featured image with a slider based on the first gallery in a post.

function gallerize_pro_filter_the_content( $content ) {
  $pattern = get_shortcode_regex();
  // http://php.net/manual/en/function.preg-match-all.php
  if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) && array_key_exists( 2, $matches ) && in_array( 'gallery', $matches[2] ) ) {
    $index = 0;
    $count = 0;
    // Remove the first gallery shortcode from the content
    foreach( $matches[2] as $match ) {
      if( $match == 'gallery' ) {
        // Found our first gallery
        $index = $count;
        break; // We've done enough
      }
      $count++;
    };
    // Remove first gallery from content
    $content = str_replace( $matches[0][$index], '', $content );
  }
  return $content;
}
add_filter( 'the_content', 'gallerize_pro_filter_the_content' );

This uses get_shortcode_regex to combine all shortcode tags into a regular expression. Then search for matches using preg_match_all and assigns them to the $matches variable. We check that ‘gallery’ is one of the terms allocated to $matches and if it is we iterate through each element so that we can identify the first instance. Finally, we remove it from the_content using str_replace.

Leave a Reply

Your email address will not be published. All fields are required.