后期保存后(使用save_post hook) 您可以检查保存的帖子是否有您的“唯一”类别,如果有,请从其他帖子中删除该类别,保留您刚刚保存的帖子。
add_action( \'save_post\', \'set_post_unique_category\', 10,3 );
function set_post_unique_category( $post_id, $savedPost, $update ) {
// Only set for post_type = post
if ( \'post\' !== $savedPost->post_type ) {
return;
}
// Check if post has your desired category
if ( ! has_category(\'best-post\', $savedPost) ){ //use your category slug
return;
}
// Get the best-post category term by its slug
$term = get_term_by( \'slug\', \'best-post\', \'category\' );
//Now let\'s find the other posts with your category
$args = array( \'category\' => $term->term_id, \'post_type\' => \'post\' ); //set the arguments for the query
$postsList = get_posts( $args );
foreach ($postsList as $post) { //Remove the category from the found posts
if ($post->ID == $post_id ) //but skip the just saved post
continue;
wp_remove_object_terms( $post->ID, \'best-post\', \'category\' );
}
}
我没有测试它,因此您可能会遇到语法错误或错误的属性名称,但逻辑应该很好,至少可以让您了解应该做什么。好的谷歌搜索加上wordpress codex漫步永远是你的朋友;)