daily pastebin goal
59%
SHARE
TWEET

Untitled

a guest Jan 23rd, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ###########
  2. // restrikcija posameznih kategorij za grupo ki je subscriber
  3. // source: https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin
  4. add_filter('template_include', 'restict_by_category');
  5.  
  6. function check_user() {
  7.   $user = wp_get_current_user();
  8.   $restricted_groups = array('company1', 'company2', 'company3', 'subscriber'); // categories subscribers cannot see
  9.   if ( ! $user->ID ||  array_intersect( $restricted_groups, $user->roles ) ) {
  10.     // user is not logged or is a subscriber
  11.     return false;
  12.   }
  13.   return true;
  14. }
  15.  
  16. function restict_by_category( $template ) {
  17.   if ( ! is_main_query() ) return $template; // only affect main query.
  18.   $allow = true;
  19.   $private_categories = array('podjetje', 'personal', 'nekategorizirano', 'razno', 'sola-2'); // categories subscribers cannot see
  20.   if ( is_single() ) {
  21.     $cats = wp_get_object_terms( get_queried_object()->ID, 'category', array('fields' => 'slugs') ); // get the categories associated to the required post
  22.     if ( array_intersect( $private_categories, $cats ) ) {
  23.       // post has a reserved category, let's check user
  24.       $allow = check_user();
  25.     }
  26.   } elseif ( is_tax('category', $private_categories) ) {
  27.     // the archive for one of private categories is required, let's check user
  28.     $allow = check_user();
  29.   }
  30.   // if allowed include the required template, otherwise include the 'not-allowed' one
  31.   return $allow ? $template : get_home_url();//get_template_directory() . '/not-allowed.php';
  32. }
  33. ###########
  34.    
  35. add_filter( 'pre_get_posts', 'hide_private_cats', 10);
  36.  
  37. function hide_private_cats($query) {
  38.     if (is_admin() || check_user()) {
  39.         return $query; // If this is an admin page or your user check passes, do nothing
  40.     }
  41.     $query->set('category__not_in', array( 3, 8, 10 )); // don't show posts that are in the categories specified (only takes IDs)
  42.     return $query;
  43. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top