Want to insert shortcode into WordPress menu? Use following code in your theme’s functions.php file OR in site specific plugin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /** * 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' ); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.