WordPress

Accueil » Coding » Exclude some pages and/or posts from the WordPress back-office except for a given user

When delivering a site to a customer, there are some pages that contain what are commonly called “tags” (features that are treated in the back office, special formatting, shortcodes or even “functions”) that should NOT be modified otherwise display or rendering “bugs”.

This or these pages/posts, therefore, have no interest in appearing in the list of documents to be edited. One can also, for a reason x or y, want to hide one or more posts. I therefore add it in the code below.

The code:

function exclude_from_admin($query) {
global $user_ID, $pagenow, $post_type;
   $the_id = get_queried_object_id();
   $exclude_posts = array(1725); /* id(s) of posts to hide */
   $exclude_pages = array(186); /* id(s) of pages to hide */
   $exclude_mix = array_merge($exclude_posts, $exclude_pages);
   $user_can = ($user_ID==1) ? true : false;
   if ( ! is_admin() && !$user_can ) {
      if( in_array($the_id, $exclude_mix) ) add_action( 'admin_bar_menu', 'remove_edit_node', 99 );
      return $query;
   }
   if ( !$user_can && $pagenow == 'edit.php') {
      if($post_type == 'page' )
         $query->query_vars['post__not_in'] = $exclude_pages;
      elseif ($post_type == 'post' )
         $query->query_vars['post__not_in'] = $exclude_posts;
   }
}
add_filter( 'parse_query', 'exclude_from_admin' );
function remove_edit_node( $wp_admin_bar ) {
   $wp_admin_bar->remove_node( 'edit' );
}

Use:

  • add the code above in the “functions.php” file of your theme (or child theme),
  • In the “$exclude_posts” variable, enter the id of the items you want to hide in the WordPress admin interface, separated by commas.
  • In the “$exclude_pages” variable, enter the id of the pages you want to hide in the WordPress admin interface, separated by commas.

To know these famous “id”, nothing easier. In the list of posts or pages to be modified, place your cursor above the “Modify” link for the one that interests you, you will see in the status bar of your browser a link in the form:
https://www.domain.tld/wp-admin/post.php?post=1249&action=edit
Write down all the “ids” you want to hide, duplicate the same with the pages and add those lists to your “functions.php” file as shown above.

In a future article, we will see how to allow users of the site to modify these “sensitive” pages but informing them that they must take precautions by handling them 🙂 …

 

If you wish to help me to make this blog alive, you can make a donation, below :).
Processing ...
USD

 

Après avoir visité les coulisses, découvrez le site :) !

Submit a Comment

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

Accueil » Coding » Exclude some pages and/or posts from the WordPress back-office except for a given user
Share This