X

Check if shortcode already exists

This is a great little snippet to check if a shortcode already exists. Usage is just as simple add this snippet to the functions.php of your WordPress theme. Then you can do the following if(shortcode_exists('gallery')){ ... } and this would return true as [gallery] shortcode already exists in WordPress by default.


Code Snippet:


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


Code Snippet:


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.


Code Snippet:


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

}

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!