Skip to content

Instantly share code, notes, and snippets.

@Viper007Bond
Created November 16, 2011 01:28
Show Gist options
  • Save Viper007Bond/1368983 to your computer and use it in GitHub Desktop.
Save Viper007Bond/1368983 to your computer and use it in GitHub Desktop.
Modify all posts
<?php
/**
* Fetching all posts from the database would suck up a lot of memory.
* So instead this code processes 25 posts at a time.
*/
$posts_at_a_time = 25;
$query_args = array(
'posts_per_page' => $posts_at_a_time,
'offset' => 0,
// Improve performance
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'no_found_rows' => true,
);
$some_posts = new WP_Query( $query_args );
// Keep looping while posts were found
while ( $some_posts->post_count > 0 ) {
// Loop through each found post
while ( $some_posts->have_posts ) {
$the_query->the_post(); // Set the $post global and some other stuff
// Clone the post
$modified_post = (array) $post;
// Modify the post
$modified_post['the_content'] .= "\n\n This new string is now on the end of the post.";
// Save the modifcations
wp_update_post( $modified_post );
}
// Get another chunk of posts to process
$query_args['offset'] = $query_args['offset'] + $posts_at_a_time;
$some_posts = new WP_Query( $query_args );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment