Restrict a page or category from specific WordPress user(s) or role(s)

add_action( 'init', 'my_block_users' );
function my_block_users() {
	if ( (!current_user_can('administrator') && !current_user_can('editor') && get_current_user_id() !== 4 ) 
		&& ( is_page('restritcted-page') || in_category( 'restricted-category' ) ) ) {
			wp_redirect( site_url('/blog/'), 403 );
			exit;
	}
}Code language: PHP (php)

Also, to exclude these pages and categories from the site:

add_filter('pre_get_posts', 'my_exclude_category');
function my_exclude_category($query) {
	if ( ($query->is_home || $query->is_archive) && !is_page('restritcted-page') ) {
		$query->set('cat', '-63'); // The category id you want to exclude
	}
	return $query;
}Code language: PHP (php)

Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.