How do I use shortcodes with PHP to swap Nav Menus
-
Hey everyone! I’m attempting to use menu locations to exchange Logged In / Logged Out menus for a user. I’ve found a great resource here that shows how to go about doing this with your main menu, but I guess I’m a masochist because I’m trying to do this with an alternative menu in a dropdown widget area on the page. There are lots of reasons why I think this would be a great solution; like changing the conditional later in development to allow navigation for CMS pages for other user roles as required, and I’d prefer not to use plugins.
The menu registration in functions.php:
function register_my_menus() { register_nav_menus( array( 'employee-menu' => __( 'Conditional Menu' ), ) ); } add_action( 'init', 'register_my_menus' );
The shortcode writeup:
function print_menu_shortcode($atts, $content = null) { extract(shortcode_atts(array( 'name' => null, ), $atts)); return wp_nav_menu( array( 'menu' => $name, 'echo' => false ) ); } add_shortcode('menu', 'print_menu_shortcode');
and finally, the shortcode plugged into the text widget. There is a great resource for this here.
[menu name="Logged In"]
The shortcode definitely works for calling a specific menu. I need it to call a menu location like ’employee-menu’ with shortcode so I can have the conditional switch out specific menus, and then have the location updated in functions.php
Here’s the current condition arguement:
function my_wp_nav_menu_args( $args = '' ) { if( is_user_logged_in() ) { $args['employee-menu'] = __( 'logged-in' ); } else { $args['employee-menu'] = __( 'logged-out' ); } return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
If it helps to visualize what I mean, the WEBSITE has a little + arrow in the upper right corner with the widget area in question.
I hope it’s clear what I’m intending, and thanks in advance for your time! ??
- The topic ‘How do I use shortcodes with PHP to swap Nav Menus’ is closed to new replies.