Remove a category from a post when saving a new post

Question

I’m having problems with my code. I’m trying to remove a category from a post that’s using that category and then adding that same category when saving a post.

For example, if I have a post that’s using "First post", when saving any post that is using that category gets removed and the new post that’s being saved is added to the category "First post".

The code I’m using adds the category when saving a post but the previous post that’s using that category doesn’t get removed.

Here’s my code:

function save_category($post_ID){
// get all posts using 'First post' category
$categories =  wp_get_object_terms( $post_ID, 'First post' );
// query to get posts using 'First post' category
if ($categories) {
    foreach ($categories as $key => $category)
    // if post is using 'First post' category then remove the category
    if ($category->name == "First post") {
        wp_remove_object_terms( $post_ID, 'First post', 'category' );
    }
    return;
}
// Add 'First post' to post when saving
wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) ); 
}
add_action('save_post', 'save_category');
0
OpenBayou 2 months 0 Answers 22 views 0

Leave an answer