How to insert shortcode in wordpress menu

I made a menu item with this code. A menu item is displayed, but there is no shortcode output. Is there something I can add, or another method that will do this. I also added that this might help.

add_filter('wp_nav_items', 'do_shortcode', 7); 

Or maybe someone knows that this is impossible and can tell me.

 /* Nav Menu */ function add_profile_link_to_nav(){ if ( is_user_logged_in() ) { ?> <ul> <li class="menu-item"id="one"> <a href="http://example.com/members/">All Members</a> <ul class="sub-menu"> <li class="menu-item"><?php echo custom_execute_shortcode(); ?> </li> </ul> </li> </ul> <!--end menu---> <?php } } add_action( "wp_nav_items","add_profile_link_to_nav" ); function custom_execute_shortcode() { $myfunction= '[my shortcode"]'; $myfunction_parsed = do_shortcode($myfunction); return $myfunction_parsed; } 

thanks

+6
source share
2 answers

You cannot use shortcodes directly in the menu URL on the menu page, as the brackets fail. But you can use placeholders as follows: #profile_link# .

Using the following code in functions.php you can create a custom menu item with the URL #profile_link# and it will replace it with your short code.

 /** * 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 the 'shortcode' to the $placeholders array and optionally 'atts' and 'content' .

For example, if your short code looks like this:

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

Would you update:

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

Please note that I do not use do_shortcode() , because it is a resource-intensive function and is not suitable for work in this case.

+6
source

@ Tim This code will work

put it in functions.php file

 add_filter('wp_nav_menu_items', 'do_shortcode'); 
+13
source

Source: https://habr.com/ru/post/920078/


All Articles