Enable WordPress shortcodes for menu and widgets

Imagine you want to show your related posts in the sidebar, social share icons in the navigation, or anything else you created a shortcode for.

By default, you can’t add a shortcode to your navigation menu or as widgets (footer, sidebar…). However, since the text from a text widget runs trough a filter called widget_text, enabling them is pretty easy.

Make sure to use this in combination with shortcode_unautop. This will ensure you that the output of our shortcode callback is not wrapped in paragraph tags.

Add a priority so that do_shortcode runs after wpautop. The default filter priority for shortcodes in posts is 11 (source).

Add the following PHP code to your child-themes’ functions.php

Enable shortcodes for menu navigation:

/**
 * Enable shortcodes for menu navigation.
 */
if ( ! has_filter( 'wp_nav_menu', 'do_shortcode' ) ) {
    add_filter( 'wp_nav_menu', 'shortcode_unautop' );
    add_filter( 'wp_nav_menu', 'do_shortcode', 11 );
}

Enable shortcodes for widgets (footer, sidebar…):

/**
 * Enable shortcodes for widgets (footer, sidebar...).
 */
if ( ! has_filter( 'widget_text', 'do_shortcode' ) ) {
    add_filter( 'widget_text', 'shortcode_unautop');
    add_filter( 'widget_text', 'do_shortcode', 11);
}

That’s it! ✌️

Support 🐶

If you found this article helpful, got a question or spotted an error/typo... Do well to leave your feedback in the comment section or help spread it by sharing this article. If you're feeling generous (and I hope you do) you can definitely help me by getting me a cup of coffee ☕.


You may like these too!

Leave a Reply

Your email address will not be published.