I have a category called "best post". When the editor selects this category in a post and publishes the page, a PHP routine must check if other posts have this category, and if so, this category must be deleted from all posts except the current page...
1 Answer
After the post save (using save_post hook) you check if the saved post has your "unique" category, and if so remove the category from the other posts, keeping the one you just saved.
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' );
}
}
I haven't tested it so you could encounter syntax errors or wrong property names, but the logic should be fine, at least to get you an idea of what you should do. A good google search plus a wordpress codex stroll are always your friends ;)
-
works well ! Small issue: when you do an "inline edit" , the front-end doesn't get refreshed even if everything goes well on the back end: so a refresh is needed Feb 13, 2019 at 8:44
-
in that case you should find which filters are involved in the inline editing and hook similar code to them Feb 13, 2019 at 9:08