0

I’d like to set a custom taxonomy as required, i.e. authors must select at least one term from the taxonomy in order to save or update a post of a specified set of custom post type. If they haven't done that, a custom error message displays.

I’m registering taxonomies using Extended CPTs, for example:

<?php
// Topic taxonomy
// Docs: https://github.com/johnbillion/extended-cpts/wiki/Registering-taxonomies
add_action('init', function () {
  register_extended_taxonomy('topic', [
    'article',
    'event',
    'resource',
  ], [
    'exclusive' => false,
    'hierarchical' => false,
    'meta_box' => 'simple', // supports multiple (non-exclusive)
    'public' => true, // applies to “publicly_queryable”, “show_ui”, and “show_in_nav_menus”
    'query_var' => true,
    'required' => true,
    'show_admin_column' => true,
    'show_in_quick_edit' => true,
    'show_in_rest' => true,
  ], [
    'singular' => 'Topic *',
    'plural' => 'Topics',
    'slug' => 'topic',
  ]);
});

How can this be accomplished (ideally, without using jQuery)?

1 Answer 1

0

You could consider using the wp_insert_post_empty_content hook. This hook determines if a post is considered empty and if so, prevents it from being saved. For example:

/**
 * Checks whether some post types have a topic.
 *
 * @param bool  $maybe_empty Whether the post should be considered "empty".
 * @param array $postarr     Array of post data.
 * @return bool Whether the post is empty.
 */
function my_plugin_require_topic( $maybe_empty, $postarr ) {
  if ( ! $maybe_empty && in_array( $postarr['post_type'], array( 'article', 'event', 'resource' ), true ) {
    $maybe_empty = empty( $postarr['tax_input']['topic'] );
  }

  return $maybe_empty;
}
add_filter( 'wp_insert_post_empty_content', 'my_plugin_require_topic', 10, 2 );

For how to implement the custom error message, that would depend on where you want the error message surfaced. This is because there are multiple ways that a post could be edited, and surfacing the error message would depend on the interface you'd want to target.

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.