X

How to Check If Shortcode Already Exists in WordPress

Snippets by IsItWP

Are you looking for a way to check if shortcode already exists? Before you attempt to create a new shortcode from scratch, it’s best to search your WordPress site. While there’s probably a plugin for this, we have created a quick code snippet that you can use to check if shortcode already exists in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

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

Add this code on your theme’s index.php file to check if shortcode already exists.

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 [gallery] shortcode already exists. Another plugin may already be using it.</p>
        </div>
        <?php

}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 28 best WordPress resume themes and how to create a multi-page form in WordPress.

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!