X

Check If Shortcode Already Exists

Need a shortcode for something? There's a good chance one already exists on your site! Before you attempt to make one from scratch, use this snippet to find out if there's already one available for you to use.

Just add this snippet to the functions.php of your WordPress theme. Then, you can test it by doing the following: if(shortcode_exists('gallery')){ ... } This will return ‘true’ as the [gallery] shortcode already exists in WordPress by default.

  function shortcode_exists( $shortcode = '' ) {
	global $shortcode_tags;
	if ( $shortcode && array_key_exists( $shortcode, $shortcode_tags ) ){
		return true;
	}else{
		return false;
	}
  }
if(shortcode_exists('gallery')){
    echo 'Gallery shortcode exists';
}

You could integrate this snippet into a plugin to check and make sure the shortcode you register doesn’t exist. If this shortcode does exist you would be able to warn users of the conflict with an admin notice. This sample will check for the existence of [gallery] and then display an admin error message.

if(shortcode_exists('gallery')){
   add_action( 'all_admin_notices', 'wpsnipp_custom_admin_notice' );
}

function wpsnipp_custom_admin_notice() {
        ?>
        <div id="message" class="error notice is-dismissible">
            <p><b>Error:</b> Sorry but  shortcode already exists. Another plugin may already be using it.</p>
        </div>
        <?php

}

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!