if role is logged in then do something

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 .= 'lia href=/product-category/public/SCHOOL_NAME/ class=navShopNow fungulaSHOP NOW ADMIN/a/li';
    }

    //School ROLEABC
            elseif (current_user_can('ROLEABC')  is_user_logged_in  $args-menu-5) {
                    $items .= 'lia href=/product-category/public/SCHOOL_NAME/ class=navShopNow fungulaSHOP NOW ABC/a/li';
            }
    //School ROLEXYZ
            elseif (current_user_can('ROLEXYZ')  is_user_logged_in  $args-menu-5) {
                    $items .= 'lia href=/product-category/public/SCHOOL_NAME/ class=navShopNow fungulaSHOP 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, :)

Topic user-access user-roles filters menus Wordpress

Category Web


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;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.