This is proving to be a challenge.

I’m trying to make the excerpt a required field, but only when editing/saving a post in a custom post type.

The following code makes the excerpt a required field for all posts, but doesn’t take into account for narrowing its affect to a single custom post type.

function mandatory_excerpt($data) {
  $excerpt = $data['post_excerpt'];

  if (empty($excerpt)) {
    if ($data['post_status'] === 'publish') {
      add_filter('redirect_post_location', 'excerpt_error_message_redirect', '99');
    }

    $data['post_status'] = 'draft';
  }

  return $data;
}

add_filter('wp_insert_post_data', 'mandatory_excerpt');

function excerpt_error_message_redirect($location) {
  remove_filter('redirect_post_location', __FILTER__, '99');
  return add_query_arg('excerpt_required', 1, $location);
}

function excerpt_admin_notice() {
  if (!isset($_GET['excerpt_required'])) return;

  switch (absint($_GET['excerpt_required'])) {
    case 1:
      $message="Excerpt is required to publish a post.";
      break;
    default:
      $message="Unexpected error";
  }

  echo '<div id="notice" class="error"><p>' . $message . '</p></div>';
}

add_action('admin_notices', 'excerpt_admin_notice');

4 s
4

The code adds a filter to wp_insert_post_data:

add_filter('wp_insert_post_data', 'mandatory_excerpt');

And here’s the callback:

function mandatory_excerpt($data) {
  $excerpt = $data['post_excerpt'];

  if (empty($excerpt)) {
    if ($data['post_status'] === 'publish') {
      add_filter('redirect_post_location', 'excerpt_error_message_redirect', '99');
    }

    $data['post_status'] = 'draft';
  }

  return $data;
}

The filter callback is passed $data, which as per the Codex includes the following post data:

'post_author',
'post_date',
'post_date_gmt',
'post_content',
'post_content_filtered',
'post_title',
'post_excerpt',
'post_status',
'post_type',
'comment_status',
'ping_status',
'post_password',
'post_name',
'to_ping',
'pinged',
'post_modified',
'post_modified_gmt',
'post_parent',
'menu_order',
'guid'

Those data include 'post_type', which means you can use that inside the callback:

function mandatory_excerpt($data) {
    if ( 'custom-posttype-slug' != $data['post_type'] ) {
        return $data;
    } else {
        $excerpt = $data['post_excerpt'];

        if (empty($excerpt)) {
            if ($data['post_status'] === 'publish') {
                add_filter('redirect_post_location', 'excerpt_error_message_redirect', '99');
            }     
            $data['post_status'] = 'draft';
        }
    }     
    return $data;
}

Leave a Reply

Your email address will not be published. Required fields are marked *