How to Restrict Users from Posting to a Specific Category

Hi, I’m trying to prevent non-admin users from posting to a specific category in HivePress. Currently, I am using the following code to hide category ID 66 from the category selection for non-admin users.

Here is the code I’m using:

// Hide category ID 66 from non-admin users on the listing submission form
add_filter( 'hivepress/v1/forms/listing_submit', function( $form ) {
    if ( ! current_user_can( 'manage_options' ) && isset( $form['fields']['categories'] ) ) {
        $restricted_category_id = 66;

        // Remove category ID 66 from the options
        $new_options = [];
        foreach ( $form['fields']['categories']['options'] as $term_id => $label ) {
            if ( $term_id != $restricted_category_id ) {
                $new_options[ $term_id ] = $label;
            }
        }

        $form['fields']['categories']['options'] = $new_options;
    }

    return $form;
}, 100 );

Is there a better way to achieve this? If the current code needs improvement, could you please point it out?

Thanks in advance!

Hi,

The code seems ok, you can also consider using unset to remove options from $form['fields']['categories']['options'] instead of populating a new array and overriding it. If you’re ok with showing categories but with an error when users try to select it, here’s another approach:

add_filter(
 'hivepress/v1/forms/listing_submit/errors',
 function ( $errors, $form ) {

  $listing = $form->get_model();

  if (!$listing){
   return $errors;
  }

  if ( ! current_user_can( 'manage_options' )  && in_array( 66, (array)$listing->get_categories__id()) ){
   $errors [] = 'Only admin can add listings to this category.';
  }

  return $errors;
 },
 1000,
 2
);

Hope this helps

Thank you so much for your help!
I really appreciate your quick and clear response. It helped me a lot.
Thanks again for taking the time to support the community!

1 Like