Skip to content

Instantly share code, notes, and snippets.

@manchumahara
Last active September 5, 2019 05:24
Show Gist options
  • Save manchumahara/b4930caec8119ecf258f70a6b7248d09 to your computer and use it in GitHub Desktop.
Save manchumahara/b4930caec8119ecf258f70a6b7248d09 to your computer and use it in GitHub Desktop.
Restrict any wp page or post for any role
<?php
/**
* Plugin Name: CBX Simple Restrict Content
* Description: Simple or hard coded wordpress content restrict for any role
* Author: Codeboxr
* Version: 1.0.0
* Licence: MIT
* Author URI: https://codeboxr.com
*/
//if you want to use this code in theme ignore lines from 1-10 or use code from 11 to bottom of this page.
add_action( 'wp', 'cbx_restrict_content' );
function cbx_restrict_content($content){
//write_log($content);
$post_page_id = '4565'; //post or page id which you want to restrict
$role_name = 'contributor'; //specific role name/slug
if(is_singular()){
$post_id = intval(get_the_ID());
$user_roles = array();
if( is_user_logged_in() ) {
$user = wp_get_current_user();
$user_roles = ( array ) $user->roles;
}
if($post_id == $post_page_id && !in_array($role_name, $user_roles)){
add_filter('the_content', 'cbx_restrict_content_message');
}
}
return $content;
}
function cbx_restrict_content_message(){
return 'Sorry, you are not allowed to view the content of this article/page';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment