How to Enable Shortcodes in WordPress Menus and Widgets

Shortcodes in WordPress allow users to easily add dynamic content, such as buttons, forms, or custom post types, to their posts, pages, 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, WordPress does not support shortcodes in its menu and widget areas. However, you can easily enable this functionality through the functions.php file. This tutorial provides a step-by-step guide on how to enable shortcodes in WordPress menus and widgets.

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).

Access the functions.php file: Log in to your WordPress dashboard, go to Appearance > Theme Editor, and select the functions.php file from the right-side list. Add the following code snippet:

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);
}

After adding the code, save the functions.php file and test that the shortcodes are working correctly, go to Appearance > Menus and add a shortcode to a menu item’s description or add a shortcode to a text widget.

Note: It’s crucial to be cautious when editing the functions.php file, as a small mistake in the code can result in your website not functioning correctly. To avoid any issues, it’s recommended to make a backup of the file before making any changes.

In conclusion, enabling shortcodes in WordPress menus and widgets is a simple process that can greatly enhance the functionality of your website. By following this step-by-step guide, you can easily add dynamic content to your menu and widget areas and customize your website as per your requirements. Don’t forget to make a backup of the functions.php file before making any changes to minimize the risk of any issues.

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. Required fields are marked *