Run a Shortcode Anywhere in WordPress

WordPress shortcodes are macro codes that allow you to perform certain actions within the post content. By default they only display on single post pages within the post content. The most commonly used one is probably the gallery shortcode which looks like this:
Including that in your post content will display the post’s gallery on the front end. But what if you also wanted to display your shortcode on a category page, or on any page template for that matter? That’s pretty simple thanks to an awesome function called get_shortcode_regex.
Using get_shortcode_regex we can easily put together a code snippet that will check your post content for any specific shortcode:

$pattern = get_shortcode_regex();
preg_match('/'.$pattern.'/s', $post->post_content, $matches);
if (is_array($matches) && $matches[2] == 'the_shortcode_name') {
   // do something
}

If you include the above function within the WordPress loop on a category page, it will search through the post content for a shortcode called “the_shortcode_name”. If it finds it, it will store the shortcode in the $matches variable. Now you can actually run the shortcode by making one small modification:

$pattern = get_shortcode_regex();
preg_match('/'.$pattern.'/s', $post->post_content, $matches);
if (is_array($matches) && $matches[2] == 'the_shortcode_name') {
   $shortcode = $matches[0];
   echo do_shortcode($shortcode);
}

That will find the shortcode (if it’s included in the post content) and it will run it. Include that within the WordPress loop on any page template and you can display the shortcode anywhere you want.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie