使用新的块编辑器(Gutenberg)保存帖子时,Shibi的答案不再正确,因为设置帖子术语(设置类别)的调用现在发生在save_post
操作已运行。相反,接受答案中的函数只检查旧术语,这意味着只有在使用默认类别保存帖子后第二次才会将其删除。请参见WP_REST_Post_Controller
\'supdate_item
功能(备注矿山):
public function update_item( $request ) {
// First the function updates the post. The `save_post` action is run,
// but it doesn\'t yet see the new categories for the post.
$post_id = wp_update_post( wp_slash( (array) $post ), true );
...
// Only later does the block editor set the new post categories.
$terms_update = $this->handle_terms( $post->ID, $request );
...
}
通过连接到,我以一种既适用于经典编辑器又适用于块编辑器的方式实现了所需的行为
set_object_terms
, 在块编辑器中调用
$this->handle_terms
:
/**
* Remove unnecessary "Uncategorised" category on posts saved with another, non-default
* category.
*
* This is performed on the `set_object_terms` action as part of `wp_set_object_terms` function
* because the `save_post` action, where this would logically be run, is run *before* terms are
* set by the block editor (in contrast to the classic editor).
*
* @param int $object_id Object ID.
* @param array $terms An array of object terms.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
*/
function wpse_254657_remove_superfluous_uncategorised( $object_id, $terms, $tt_ids, $taxonomy ) {
if ( \'category\' !== $taxonomy ) {
return;
}
$post = get_post( $object_id );
if ( is_null( $post ) || \'post\' !== $post->post_type ) {
return;
}
if ( count( $terms ) <= 1 ) {
return;
}
// Get default category.
$default_category = get_term_by( \'id\', get_option( \'default_category\' ), $taxonomy );
// Rebuild list of terms using $tt_ids and not the provided $terms, since
// $terms can be mixed type and is unsanitised by `wp_set_object_terms`.
$terms = array();
foreach( $tt_ids as $tt_id ) {
$term = get_term_by( \'term_taxonomy_id\', $tt_id, $taxonomy );
if ( $term ) {
$terms[] = $term;
}
}
if ( ! in_array( $default_category->term_id, wp_list_pluck( $terms, \'term_id\' ), true ) ) {
return;
}
// Remove the default category from the post.
wp_remove_object_terms( $post->ID, $default_category->term_id, \'category\' );
}
add_action( \'set_object_terms\', \'wpse_254657_remove_superfluous_uncategorised\', 10, 4 );
在上面,我还必须建立自己的
$terms
因为钩子提供的一个可以包含字符串和int的混合,也可以包含字符串和int的混合数组。因此,以这种方式获取术语更简单。用缓存WordPress这个词来说,这应该不会增加太多开销。