0
votes

I'm using a theme and within the functions.php menus are added like this:

register_nav_menus( array(
    'primary' => __( 'Main Menu', 'theme_name' ),
    'footer' => __( 'Footer Menu', 'theme_name' )   
) );

What I'm trying to do is to add - depending on if user is logged in or not - to add a login/logout link to the footer menu. I found this piece of code here:

add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {
        ob_start();
        wp_loginout('index.php');
        $loginoutlink = ob_get_contents();
        ob_end_clean();
        $items .= '<li>'. $loginoutlink .'</li>';
    return $items;
}

It works BUT it's adding the menu items to all menus. I also found this:

add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 );
function add_loginout_link( $items, $args ) {
    if (is_user_logged_in() && $args->theme_location == 'primary') {
        $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>';
    }
    elseif (!is_user_logged_in() && $args->theme_location == 'primary') {
        $items .= '<li><a href="'. site_url('wp-login.php') .'">Log In</a></li>';
    }
    return $items;
}

which also works but adds the links only to the main menu ('primary'). But how could I select my footer menu or what do I have to add to the register menu function to make it able to filter it with $args?

2

2 Answers

0
votes

I was blind. I skipped the passage with primary -> ... and footer -> ...

I could select it simply with:

add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 );
function add_loginout_link( $items, $args ) {
    if (is_user_logged_in() && $args->theme_location == 'footer') {
        $items .= '<li><a href="'. wp_logout_url() .'">Log Out</a></li>';
    }
    elseif (!is_user_logged_in() && $args->theme_location == 'footer') {
        $items .= '<li><a href="'. site_url('wp-login.php') .'">Log In</a></li>';
    }
    return $items;
}

So I just had to replace 'primary' with 'footer'... Silly me

-1
votes

According to:

function register_main_menus() {
   register_nav_menus(
      array(
         'primary-menu' => __( 'Primary Menu' ),
         'secondary-menu' => __( 'Secondary Menu' ),
         'footer-menu' => __( 'Footer Menu' ),
      )
   );
};

You can add you links like this:

add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {
    ob_start();
    wp_loginout('index.php');
    $loginoutlink = ob_get_contents();
    ob_end_clean();
    $items .= '<li>'. $loginoutlink .'</li>';
return $items;
}