17

How to Show or Hide Content Based on User Role in WordPress

Powered by WPCodeBox

Control user experience on your WordPress site by showing or hiding specific content based on user roles. This snippet allows website owners to customize content visibility for different user types, enhancing site functionality and user management.


<?php
/**
 * Author: WP Turned UP
 * Author URI: https://wpturnedup.com
 */
 
//// 1. Change the 'role_A' and ""role_B' entries to match the roles of users you want to allow to see the content.
//// 2. Add the 'showbyrole' CSS class to any elements on your website you wish to filter.

// SHOW CONTENT BASED ON ROLE
add_action('init','show_content_by_role_create_the_css');

function show_content_by_role_create_the_css() {
    $user = wp_get_current_user();
    if(! in_array('role_A', $user->roles) & ! in_array('role_B', $user->roles)) {
        add_action( 'wp_head', function () {
            echo '<style type=""text/css"">.showbyrole { display: none !important;} 
            </style>';
        });
    }
}

Other Snippets

WPCodeBox is a WordPress Code Snippets Manager that allows you to share your WordPress Code Snippets across your sites.