how to insert shortcode into wordpress menu

泪湿孤枕 提交于 2019-12-03 03:24:38

You can't use shortcodes directly in the menu URL on the menu page, because the brackets get stripped out. But you can use placeholders like this: #profile_link#.

With the following code in functions.php, you can create a custom menu item with the URL #profile_link#, and it will replace that with your shortcode.

/**
 * Filters all menu item URLs for a #placeholder#.
 *
 * @param WP_Post[] $menu_items All of the nave menu items, sorted for display.
 *
 * @return WP_Post[] The menu items with any placeholders properly filled in.
 */
function my_dynamic_menu_items( $menu_items ) {

    // A list of placeholders to replace.
    // You can add more placeholders to the list as needed.
    $placeholders = array(
        '#profile_link#' => array(
            'shortcode' => 'my_shortcode',
            'atts' => array(), // Shortcode attributes.
            'content' => '', // Content for the shortcode.
        ),
    );

    foreach ( $menu_items as $menu_item ) {

        if ( isset( $placeholders[ $menu_item->url ] ) ) {

            global $shortcode_tags;

            $placeholder = $placeholders[ $menu_item->url ];

            if ( isset( $shortcode_tags[ $placeholder['shortcode'] ] ) ) {

                $menu_item->url = call_user_func( 
                    $shortcode_tags[ $placeholder['shortcode'] ]
                    , $placeholder['atts']
                    , $placeholder['content']
                    , $placeholder['shortcode']
                );
            }
        }
    }

    return $menu_items;
}
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );

You just need to set 'shortcode' in the $placeholders array, and optionally 'atts' and 'content'.

For example, if your shortcode is like this:

[example id="5" other="test"]Shortcode content[/example]

You would update:

'#placeholder#' => array(
    'shortcode' => 'example';
    'atts' => array( 'id' => '5', 'other' => 'test' );
    'content' => 'Shortcode content';
),

Note that I don't use do_shortcode() because it is a resource intensive function and isn't the right tool for the job in this case.

@Tim This code will work

put it in functions.php file

add_filter('wp_nav_menu_items', 'do_shortcode');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!