1

I'd like to prevent posts under the default category named "affitti" to be published. I tried this but with no effect

function prevent_default_category_publish($data, $postarr) {
if (in_category('affitti', $postarr['ID'])) {
    wp_die('Error: Posts cannot be published with the default category.');
}
return $data;
}
add_filter('wp_insert_post_data', 'prevent_default_category_publish', 10, 2);
3
  • 1
    the code in your question would also prevent the creation of drafts and revisions, it's important to know are you asking for the block editor or a different editor? If it's the block editor then there are APIs that can be used to implement pre-publish checks that aren't available in the classic editor
    – Tom J Nowell
    Commented Oct 23 at 16:12
  • @TomJNowell block editor Commented Oct 23 at 16:23
  • it seems it's not possible to accomplish what I wanted in PHP [link]wordpress.org/support/topic/… Commented Oct 24 at 6:45

1 Answer 1

0

The in_category function works only on existing (saved) posts. Here you can directly access the category in $postarr like this:

if ('affitti' == $postarr['post_category'])) {
  wp_die('Error: Posts cannot be published with the default category.');
  }

By the way, are you sure you want to use wp_die for this and not some other error message? People may loose their work if WP stops completely when they try to publish.

2
  • No, I'm not sure. Any other solution? I tested the new conditional but it's not working :( I removed a parenthesis too, but it doesn help, sorry Commented Oct 23 at 15:31
  • Are you sure the filter is called at all?
    – cjbj
    Commented Oct 23 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.