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');
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Your foreach doesnt have brackets or semicolons, probably thatś why.
and also not very well idented.
Here it is the code properly idented, just one maybe, the foreach closing brackets probably must be after the return like in the code bellow, or maybe right before. if this code doesnt work cut and paste “return;” to right after the “endforeach;”.
function save_category($post_ID){ // get all posts using 'First post' category
$categories = wp_get_object_terms( $post_ID, 'First post' );
if ($categories) { // query to get posts using 'First post' category
foreach ($categories as $key => $category) :
if ($category->name == "First post") { // if post is using 'First post' category then remove the category
wp_remove_object_terms( $post_ID, 'First post', 'category' );
}
return;
endforeach;
}
wp_set_post_categories( $post_ID, get_cat_ID( "First post" ) ); // Add 'First post' to post when saving
}
add_action('save_post', 'save_category');
Method 2
I don’t see you querying for the posts that are using that category,
Use get_posts like this:
$first_posts = get_posts([
'category_name' => 'first-post', // your category slug is
]);
foreach( $first_posts as $p ) {
wp_remove_object_terms( $p->ID, 'first-post' );
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0