Skip to content

Instantly share code, notes, and snippets.

@brettkelly
Created February 15, 2023 19:44
Show Gist options
  • Save brettkelly/d113004de6399a57856d01b35669d4c6 to your computer and use it in GitHub Desktop.
Save brettkelly/d113004de6399a57856d01b35669d4c6 to your computer and use it in GitHub Desktop.
Hide an HTML element by class based on WP user role
<?php
// Hide the Inventory nav item for everybody except admins and buyers
function rw_hide_inventory_link_for_role() {
$allowed_roles = ['administrator', 'rw-buyer']; // these user roles can see the item
$hide = true; // default to hiding it
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$roles = (array)$user->roles;
foreach($roles as $role) {
if(in_array($role, $allowed_roles)) { // if this role is in allowed_roles, don't hide it
$hide = false;
}
}
}
// if hide is true, dump the CSS to hide it.
if($hide): ?>
<style>
.inventory-link { display: none !important; }
</style>
<?php
endif;
}
add_action('wp_head','rw_hide_inventory_link_for_role');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment