2

I am working on a web app word press. I am new to word press So maybe you will feel that this question is silly, I tried everything but i don't want to use any plugin.

here is what I need to show the register/login menu item to non-logged-in users and profile/logout menu item to logged-in-users. But In my website I am not using word press login function wp_login() I am using web service to get the login response and then I am using sessions to control the user data and access the user data on a different page.

On profile pages I have done

if(!isset($_SESSION['user'])){
     header("Location:http://localhost:8080/wordpress/login/");
}
else {
    //page content
}

I have tried this, but its not working

function my_wp_nav_menu_args( $args = '' ) {

if( isset($_SESSION['user']) ) { 
$args['menu'] = 'logged-in';
} 
return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

But how can i do this with menu items ??

2

1 Answer 1

5

Use the wp_nav_menu_objects filter to access the menu items

I have used this code:

add_filter('wp_nav_menu_objects', 'ad_filter_menu', 10, 2);

function ad_filter_menu($sorted_menu_objects, $args) {
    // check for the right menu to rename the menu item from
    // here we check for theme location of 'primary-menu'
    // alternatively you can check for menu name ($args->menu == 'menu_name')

    if ($args->theme_location != 'primary')  
        return $sorted_menu_objects;

    // rename the menu item that has a title of 'Log ind'
        if (is_user_logged_in()) {
            foreach ($sorted_menu_objects as $key => $menu_object) {
                // can also check for $menu_object->url for example
                // see all properties to test against:
                // print_r($menu_object); die();
                if ($menu_object->title == 'Log in') {
                    $current_user = wp_get_current_user();
                    $menu_object->title = $current_user->user_login . " - Log out";
                    $menu_object->url = wp_logout_url();;
                }
            }
        }
    return $sorted_menu_objects;
}

Found the basis for that here: Remove a menu item in menu

Obviously you need to change the line

if (is_user_logged_in()) {

to

if( isset($_SESSION['user']) ) {

and you may need to check for additional menu items to change their title and url depending on status (Logged in or out)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.