Skip links

WordPress find specific shortcodes from post & page contents

How do you find specific shortcode from the wordpress page or post contents? For a example if you are using “gallery” shortcode, you want to check that code if exist or not for some modifications.I wanted this for gallery shortcode if exist for some gallery width changes.So I found some codes and I have improved php codes and implementing here to you.

Checks whether a specific shortcode exists or not

You can use wordpress core shortcode_exists() function to this.

 if ( shortcode_exists( 'gallery' ) ) {
      // gallery shortcode is exist

But here you can’t find shortcode is exist in the post/page contents.Here I’m going to explain how to check exists specific shortcode from page or post contents.
I’m using this code inside the post/page loop.

$pattern = get_shortcode_regex();
preg_match('/'.$pattern.'/s', $post->post_content, $matches);
if (is_array($matches) && $matches[2] == 'gallery') {
         // gallery shortcode is exist in the post contents

Further, after found that shortcode you want to access that with it’s parameters.

$pattern = get_shortcode_regex();
preg_match('/'.$pattern.'/s', $post->post_content, $matches);
if (is_array($matches) && $matches[2] == 'gallery') {
        $shortcode = $matches[0]; // get shortcode with it's parameters
	echo do_shortcode($shortcode); // execute that shortcode we've found

Additional Notes

This only detects the first shortcode in the post content, though.Because of the preg_match() function.
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject.

preg_match_all('/'.$pattern.'/s', $post->post_content, $matches); // check all shortcode

Delete all shortcode tags from post contents

Simply use the strip_shortcodes() wordpess function to remove all tags.(html tags)

echo strip_shortcodes($post->post_content);