Executing Shortcodes In Hook Locations Using Functions

Shortcodes like which Gravity forms use for displaying forms won’t parse and therefore won’t work in every area of your theme.

If you paste a shortcode into your category archive description or intro text field, it won’t work.

Of course they’ll work if you paste them into a post/page or widget area (as long as you add support for shortcodes in widgets). And they’ll work if you paste them into a theme specific hook location using a plugin like Genesis Simple Hooks. This hook plugin provide’s a box you can check to execute shortcodes so they’ll parse properly.

But what if you don’t want to use a hook plugin?

What if your theme uses custom hooks but doesn’t offer a hooks plugin with a field for each hook location?

The solution is you’ll need to create a custom function and add the shortcode to it. This isn’t a bad idea because you can also choose which hook you want to use and include a conditional tag as well.

Shortcodes Outside Editor #

Add a conditional tag to control where your shortcode prints on the front end.

add_action( 'genesis_before_loop', 'execute_shortcode' );
function execute_shortcode() {
echo do_shortcode( '[shortcode_tag]' );
}

Change the genesis_before_loop hook to change the position your shortcode prints on your page.

Shortcodes On Child/Sub Pages #

Swap out your_tag with your shortcode tag in the following PHP code.

add_action( 'genesis_entry_header', 'output_shortcode_on_child_pages' );
function output_shortcode_on_child_pages() {

$post = get_post();

if ( is_page() AND $post->post_parent ) {

echo do_shortcode( '[your_tag]' );

}

}

Add to the end of your child themes functions file and change the hook and/or conditional tag top control where the shortcode outputs.

Slider Shortcodes #

Here’s an example of a custom function which includes a conditional tag for the home page and uses the genesis_header hook to display a slider in the header of a Genesis child theme on the home page only:

Gravity Forms Shortcodes #

Requires the activation of the Gravity forms plugin.

So why is this code so powerful?

Because you can execute any type of Gravity form in any of your themes hook locations using any conditionals.

The above PHP code displays the Gravity form before the posts in each category are listed on all category archive pages.

Changing the location of where you want to display your forms or any type of content which uses a shortcode is easy by modifying this custom function. All you need to do is change the shortcode, hook location and conditional tag.

Related Tutorials


Comments

One response to “Executing Shortcodes In Hook Locations Using Functions”

  1. Thanks man really, saved my life

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.