Advertisement
eventsmanager

Restrict a category to specific user role

Aug 10th, 2024
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.97 KB | None | 0 0
  1. <?php
  2. /**
  3. This snippet restricts a category to a specific user role. You can modify the $restricted_role and $restricted_category_slug accordingly.
  4.  
  5. For installation instructions, see our documentation site: http://wp-events-plugin.com/tutorials/how-to-safely-add-php-code-to-wordpress/
  6. */
  7. function restrict_event_categories_by_user_role($search_args) {
  8.     // Get the current user
  9.     $user = wp_get_current_user();
  10.  
  11.     // Define the role and category to restrict
  12.     $restricted_role = 'contributor';
  13.     $restricted_category_slug = 'contributors-only';
  14.  
  15.     // Check if the user does not have the restricted role
  16.     if (!in_array($restricted_role, $user->roles)) {
  17.         // Get the category term by slug
  18.         $restricted_category = get_term_by('slug', $restricted_category_slug, 'event-categories');
  19.  
  20.         if ($restricted_category) {
  21.             $restricted_category_id = '-' . $restricted_category->term_id; // Use negative ID to exclude
  22.  
  23.             // Ensure category is an array
  24.             if (!is_array($search_args['category'])) {
  25.                 // If it's not an array, split it by commas or initialize it as an array if empty
  26.                 $search_args['category'] = !empty($search_args['category']) ? explode(',', $search_args['category']) : array();
  27.             }
  28.  
  29.             // Check if the category is not already in the array (either included or excluded)
  30.             if (!in_array($restricted_category_id, $search_args['category']) && !in_array(ltrim($restricted_category_id, '-'), $search_args['category'])) {
  31.                 // Add the restricted category to the array to exclude it
  32.                 $search_args['category'][] = $restricted_category_id;
  33.             }
  34.  
  35.             // Convert the array back to a string if needed
  36.             $search_args['category'] = implode(',', $search_args['category']);
  37.         }
  38.     }
  39.  
  40.     return $search_args;
  41. }
  42. add_filter('em_events_get_default_search', 'restrict_event_categories_by_user_role');
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement