Home > Mobile >  if role is logged in then do something
if role is logged in then do something

Time:04-19

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/" >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/" >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/" >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, :)

CodePudding user response:

If this works, then it should not be problematic, as your links only differ in their inner text. I will assume now that your intention is exactly that. However, your code is superfluous. This is a simplified version:

if ( ! function_exists( 'add_extra_item_to_nav_menu' ) ){

function add_extra_item_to_nav_menu( $items, $args ) {
    $linkTexts = [
        'administrator' => 'SHOP NOW ADMIN',
        'ROLEABC' => 'SHOP NOW ABC',
        'ROLEXYZ' => 'SHOP NOW XYZ'
    ];
    if (($args->menu - 5) && (is_user_logged_in)) {
        $linkIndex = null;
        if (current_user_can('administrator')) $linkIndex = 'administrator';
        else if (current_user_can('ROLEABC')) $linkIndex = 'ROLEABC';
        else if (current_user_can('ROLEXYZ')) $linkIndex = 'ROLEXYZ';
        if ($linkIndex) {
            $items .= '<li><a href="/product-category/public/SCHOOL_NAME/" >' . $linkTexts[$linkIndex] . '</a></li>';
        }
    }
    return $items;

}

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

Also, you may want to pass the $items variable by address as &$items to preserve its value if it is being changed.

  • Related