How to Check If Shortcode Already Exists in WordPress (PHP Snippet)

Want to check if a shortcode already exists in WordPress? Ever since the launch of WordPress 3.6 in 2013 you can easily check to see if a shortcode has been registered in WordPress with the shortcode_exists function.

This can be useful if you’re adding functionality to your theme’s functions.php file with code snippets or creating a specific plugin for your site. Since you don’t want to overwrite existing shortcodes it’s best to check if it already exists before registering a shortcode.

<?php
if ( shortcode_exists( 'image_gallery' ) ) {
echo 'The [image_gallery] shortcode already exists';
}
if ( !shortcode_exists( 'image_gallery' ) ) {
echo 'The [image_gallery] shortcode does not exist';
}

Additionally this may be useful to check if a shortcode exists before executing a do_shortcode function in your code.

This is also ideal if you’re removing a plugin and you want to catch instances of an existing shortcode on your site without resulting in an error.

For example say you had a plugin using a [modula] shortcode but have removed it to use Envira’s shortcode [envira-gallery]. If you’re a developer you can use this snippet to have [envira-gallery] used everytime [modula] is referenced and correctly change the variables as well.


I hope this quick tip was useful! If you have any WordPress development questions let me know in the comments below.

Picture of Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way. Found this article helpful? Buy Me A Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress Tips Monthly
Get the latest from SmartWP to your inbox.