if role is logged in then do something

The question:

I need some pro eyes please.

Over all, I’m adding one button/link to the MAIN NAV depending on the logged in role.

I have this “working” code:

if ( ! function_exists( 'add_extra_item_to_nav_menu' ) ){

function add_extra_item_to_nav_menu( $items, $args ) {
    if (current_user_can('administrator') && is_user_logged_in() && $args->menu-5) {
        $items .= '<li><a href="/product-category/public/SCHOOL_NAME/" class="navShopNow fungula">SHOP NOW ADMIN</a></li>';
    }

    //School ROLEABC
            elseif (current_user_can('ROLEABC') && is_user_logged_in && $args->menu-5) {
                    $items .= '<li><a href="/product-category/public/SCHOOL_NAME/" class="navShopNow fungula">SHOP NOW ABC</a></li>';
            }
    //School ROLEXYZ
            elseif (current_user_can('ROLEXYZ') && is_user_logged_in && $args->menu-5) {
                    $items .= '<li><a href="/product-category/public/SCHOOL_NAME/" class="navShopNow fungula">SHOP NOW XYZ</a></li>';
            }

    return $items;

}

add_filter( 'wp_nav_menu_items', 'add_extra_item_to_nav_menu', 150, 2 );
}

It seems to work (it does what it’s supposed to), but it is correct?
Is it a security issue?
Did I not close it properly?

SideNote: “sometimes” the button won’t load/show on the home page only;
e.i. “the button won’t appear”,
but it always works/appears on the rest of the site.

Thanks in advance, 🙂

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Something like this would be more efficient. This is basic PHP by the way, not WP specific.

function add_extra_item_to_nav_menu( $items, $args ) {

    $roles = [
        'administrator' => [ //Role - slug name
            'SCHOOL_NAME-A', //url path - appended to the end
            'ADMIN', // can be any name - appended to SHOP NOW button
        ],
        'ROLEABC' => [
            'SCHOOL_NAME-B',
            'ABC',
        ],
        'ROLEXYZ' => [
            'SCHOOL_NAME-C',
            'XYZ',
        ],
    ];

    foreach ( $roles as $role => $menu ) {
        if ( current_user_can( $role ) && is_user_logged_in() && $args->menu-5 ) {
            $items .= '<li><a href="/product-category/public/' . $menu[0] . '/" class="navShopNow fungula">SHOP NOW ' . $menu[1] . '</a></li>';
            break;
        }
    }

    return $items;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment