Run a Shortcode Anywhere in WordPress
by Bandicoot Marketing on | Posted in Tutorials | 7 comments
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: [gallery]
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.
7 comments for “Run a Shortcode Anywhere in WordPress”