Showing a menu item to a particular menu item to only one user role in Wordpress - Without any plugin

Then checked for user role whether the user there is wholesale customer or not.It does it pretty simple way if the user is wholesale it exits and if the user is different , it hides the menu link.


1 min read
Showing a menu item to a particular menu item to only one user role in Wordpress - Without any plugin

Hi,  

I recently worked on a designers site who sells some of his stuff to wholesale users and asked me to show a menu link exclusively to them.

There are numerous ways of doing it using plugins available

  1. Nav Menu Roles By Kathy Darling
  2. User Menus – Nav Menu Visibility By Code Atlantic

the above two are used widely to achieve this, but I never like to bloat a site with the code I never need so I created a simple snippet to do the task.

I started with adding a function which adds css code to the head.

add_action('init','custom_css_wholesale_customer');
function custom_css_wholesale_customer(){

Then checked for user role whether the user there is wholesale customer or not.
It does it pretty simple way if the user is wholesale it exits and if the user is different , it hides the menu link.

/**
 * @snippet       Hide Menu For a user role 
 * @author        Naveen Yellamaddi https://premiumwp.ncy.design
 * @compatible    WordPress 5.3
 */
 
add_action('init','custom_css_wholesale_customer');

function custom_css_wholesale_customer(){

$user = wp_get_current_user();

if ( ! in_array( 'wholesale_customer', (array) $user->roles ) ) {

add_action( 'wp_head', function () {

echo '<style type="text/css">.wholesale-hide{ display: none !important;} 

</style>';
});

}

}

It has limitless possibilities to hide, you can add the class of the element which you are looking to hide and easily hide it for that user role.

How to add this snippet?

You can add this snippet to your child themes functions.php , We don't recommend adding code to your main theme if its not developed by you. Otherwise you can use a simple plugin https://wordpress.org/plugins/code-snippets/

Express your views in the comment section below.

GO TOP

🎉 You've successfully subscribed to NCY Design !
OK