Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thegulshankumar/da9a8ca37a9ac220b49cb4fb0be5c0d2 to your computer and use it in GitHub Desktop.
Save thegulshankumar/da9a8ca37a9ac220b49cb4fb0be5c0d2 to your computer and use it in GitHub Desktop.
Restoring Category Assignments: Reconnecting Posts with their Category
<?php
/*
Yikes! I deleted a category in WordPress by mistake. Now what?
Well, if you have an old backup, you can extract the list of Post IDs from that specific category.
This is an alternative approach to restoring the entire backup.
Let's say the category name was 'College & Admission' with the slug 'college-admission'.
So, using the code below, we can get the list of all posts that were previously linked to 'college-admission':
*/
// Define the category slug
$category_slug = 'college-admission';
// Get the category ID using the slug
$category = get_category_by_slug($category_slug);
if ($category) {
$category_id = $category->term_id;
// Query posts in the specified category
$args = array(
'posts_per_page' => -1, // Get all posts
'category' => $category_id,
'fields' => 'ids', // Retrieve only post IDs
);
$posts = get_posts($args);
// Check if there are posts in the category
if ($posts) {
// Output the list of post IDs separated by commas
echo implode(', ', $posts);
} else {
echo "No posts found in the '$category_slug' category.";
}
} else {
echo "Category '$category_slug' not found.";
}
/*
Once this information is ready, create a new category at the site where you accidentally deleted it.
Run the code below in the functions.php file. You should be able to reassign the category to all such previous posts.
*/
// Define the category slug
$new_category_slug = 'new-category-slug';
// Get the category ID using the slug
$new_category = get_category_by_slug($new_category_slug);
if ($new_category) {
$new_category_id = $new_category->term_id;
// Array of post IDs to be assigned to the new category
$post_ids = array(/* Insert the comma-separated list of post IDs here */);
// Assign each post to the new category
foreach ($post_ids as $post_id) {
wp_set_post_categories($post_id, array($new_category_id), true); // true to append category
}
echo "Posts assigned to the '$new_category_slug' category successfully.";
} else {
echo "Category '$new_category_slug' not found.";
}
// Congrats! done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment