Disallow a user to post in certain categories

I am writing a plugin that will disallow user to post in certain categories. I am trying to display an error message to the user when he tries to post in the restricted category and also want WP should not post the same to Database. I am trying to do this using the save_post hook. However, I am stuck on how to tell WordPress not to save this post.

function buc_validatePostUpdate($post_id) {
    global $wpdb, $user_ID;     
    $buc_values = get_user_meta($user_ID,'buc_user_cat');
    $buc_final = explode(',', $buc_values[0]);

    $post_cat = get_the_category($post_id);

    foreach($post_cat as $cat) {
        if(in_array( $cat->term_id, $buc_final ) !== FALSE) {           
        }
        else {
            //At this place, I need to tell WordPress not to update the post and return back.
            add_action( 'admin_notices', 'custom_error_notice' );
            return false;
        }
    }
}
add_action( 'save_post', 'buc_validatePostUpdate' );


function custom_error_notice(){
     echo '<div class="error"><p>Error!!!!</p></div>';
     remove_action( 'admin_notices', 'custom_error_notice' );
}

EDIT 1

While searching further, I got this link at WA. I am not sure if I need to implement something similar to as mentioned in this question.

Any advice would be greatly appreciated. Thanks in advance.

1 Answer
1

save_post is too late. Look at the source and you can see that the post has already been saved when that hook fires. You will have to interrupt the process well before that hook if you want to prevent saving.

I think I would lean toward something like this:

add_filter(
  'post_updated_messages',
  function($messages) {
    $messages['post'][11] = 'This is my new message';
    return $messages;
  }
);
add_action(
  'load-post.php',
  function () {
    // summarily kill submission
    // and redirect back to edit page
    // purely to demonstrate the process
    $redir = admin_url('post.php?action=edit&message=11');

    if (
      isset($_POST['post_ID']) && ctype_digit($_POST['post_ID'])
    ) {
      $redir .= '&post=".(int)$_POST["post_ID'];
      //    var_dump($redir); die;
      wp_redirect($redir);
      die();
    }

  }
);

Your buc_validatePostUpdate code would run in the anonymous function with the // summarily kill submission comment and inside the if conditional.

Caution: This code is very crude. I am 100% sure that it will do things not intended. Use it as a springboard only. It is not final production code.

Leave a Comment