Wordpress - How to check if a shortcode exists?

#23572 introduced shortcode_exists() into 3.6.


I think you could use the following code to do this:

$content = get_the_content();
//write the begining of the shortcode
$shortcode = '[gallery';

$check = strpos($content,$shortcode);
if($check=== false) {
  //Code to execute if there isn't the shortcode
} else {
  //Code to execute if the shortcode is present
}

(Caveat: not tested)


You can create your own function,

// check the current post for the existence of a short code
function has_shortcode( $shortcode = NULL ) {

    $post_to_check = get_post( get_the_ID() );

    // false because we have to search through the post content first
    $found = false;

    // if no short code was provided, return false
    if ( ! $shortcode ) {
        return $found;
    }
    // check the post content for the short code
    if ( stripos( $post_to_check->post_content, '[' . $shortcode) !== FALSE ) {
        // we have found the short code
        $found = TRUE;
    }

    // return our final results
    return $found;
}

The in your template write a conditional like,

if(has_shortcode('[gallery]')) {  
    // perform actions here  
} 

Idea from this NetTuts link