Skip to content

Instantly share code, notes, and snippets.

@apermo
Created November 11, 2021 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apermo/1bd879d58b790a799f763a7f2e88f92c to your computer and use it in GitHub Desktop.
Save apermo/1bd879d58b790a799f763a7f2e88f92c to your computer and use it in GitHub Desktop.
Bulk move and delete Categories in WordPress
<?php
if ( ! defined( 'PHP_SAPI' ) || PHP_SAPI !== 'cli' ) {
exit( 'You shall not pass' );
// echo '<pre>';
// set_time_limit( 0 );
}
$dir = $argv[1] ?? __DIR__;
// Load wp-config to make sure we can use WordPress.
if ( ! is_readable( $dir . '/wp-config.php' ) ) {
exit( 'Could not find wp-config, please add the correct path to the wp-config.php to the cli command' );
}
require_once $dir . '/wp-config.php';
if ( ! defined( 'ABSPATH' ) ) {
exit( 'You shall not pass' );
}
if ( ob_get_level() ) {
echo ob_get_flush(); // phpcs:ignore HM.Security.EscapeOutput.OutputNotEscaped
}
$mapping = [
// Dublicate => correct category
1 => 2,
3 => 4,
];
foreach ( $mapping as $duplicate_category => $correct_category ) {
echo 'Updating ' . $duplicate_category . PHP_EOL;
$args = [
'numberposts' => -1,
'category' => $duplicate_category,
];
$posts = get_posts( $args );
echo 'Found ' . count( $posts ) . ' Posts' . PHP_EOL;
$errors = 0;
$success = 0;
foreach ( $posts as $post ) {
$categories = $post->post_category;
// Remove the broken category.
$categories = array_diff( $categories, [ $duplicate_category ] );
// Add the correct one.
$categories[] = $correct_category;
// Remove Duplicates if any.
$categories = array_unique( $categories );
// Write this to WordPress.
$result = wp_set_post_categories( $post->ID, $categories );
if ( $result === false || $result instanceof WP_Error ) {
echo 'Error on updating ' . $post->ID . PHP_EOL;
$errors++;
} else {
echo 'Updated ' . $post->ID . PHP_EOL;
$success++;
}
}
echo 'Success: ' . $success . PHP_EOL;
echo 'Errors: ' . $errors . PHP_EOL;
$result = wp_delete_category( $duplicate_category );
if ( $result === true ) {
echo 'Deleted Category ' . $duplicate_category . PHP_EOL;
} else {
echo 'Failed deleting Category ' . $duplicate_category . PHP_EOL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment