Skip to content

Instantly share code, notes, and snippets.

@Viper007Bond
Created February 16, 2012 08:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Viper007Bond/1843275 to your computer and use it in GitHub Desktop.
Save Viper007Bond/1843275 to your computer and use it in GitHub Desktop.
WordPress: Add Another Category To Posts
<?php
/**
* Takes posts that are in category A and also adds them to category B
*/
// Uncomment this to proceed
exit( "You need to edit the file and enter the hostname and category IDs.\n" );
// What blog? Asking for both for safety reasons.
$target_blog_id = 0;
$_SERVER['HTTP_HOST'] = 'site.com'; // Mapped domain
// What's the category ID to pull posts from?
$source_category = 123;
// What's the category ID to add?
$add_category = 456;
# Okay, stop editing! :)
function free_up_memory() {
global $wpdb, $wp_object_cache;
$wpdb->queries = array(); // or define( 'WP_IMPORTING', true );
if ( ! is_object( $wp_object_cache ) )
return;
$wp_object_cache->group_ops = array();
$wp_object_cache->stats = array();
$wp_object_cache->memcache_debug = array();
$wp_object_cache->cache = array();
$wp_object_cache->__remoteset(); // important
}
define( 'WP_IMPORTING', true );
define( 'SAVEQUERIES', false );
set_time_limit( 0 );
ini_set( 'memory_limit', '768M' );
require_once( dirname( __FILE__ ) . '/../../wp-load.php' );
switch_to_blog( $target_blog_id );
// Safety check
$blog_url = 'http://' . $_SERVER['HTTP_HOST'];
if ( $blog_url != home_url() )
exit( "Blog ID {$target_blog_id} is " . home_url() . ", not {$blog_url}. Please check the blog ID and the HTTP_HOST.\n" );
// Build query args
$posts_at_a_time = 50;
$args = array(
'category__in' => array( $source_category ),
'posts_per_page' => $posts_at_a_time,
'offset' => 0,
// Prevent new posts from affecting the order
'orderby' => 'ID',
'order' => 'ASC',
// Speed this up
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
);
// Get the first set of posts
$query = new WP_Query( $args );
$found_posts = 0;
// Start looping through chunks of posts
while ( $query->have_posts() ) {
foreach ( $query->posts as $post ) {
echo '.';
$found_posts++;
wp_set_object_terms( $post->ID, array( $add_category ), 'category', true );
}
free_up_memory();
// Get more posts to process
$args['offset'] = $args['offset'] + $posts_at_a_time;
$query = new WP_Query( $args );
}
echo "\nAll done! Updated {$found_posts} posts.\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment