You are here: Home . Code, WordPress . WordPress Tutorial: Update all posts at once

WordPress Tutorial: Update all posts at once

WordPress only allows you to update certain fields (like author, status, tags) for several posts at once from the admin section of your site. What do you do though if you’d like to update fields the WordPress admin section won’t allow you to? What happens if, for example, you’d like to change the post titles of all posts in a particular category? This can be done using a bit of code I’ll walk you through here.

Update 08/08/2015: Changed the code based on feedback

If, for example, you’d like to add a prefix ‘Post Prefix’ to every post in category with ID x, you’d use the following code:

        $posts_to_update = get_posts('cat=x&showposts=1000');//Retrieve the posts you are targetting
        foreach ( $posts_to_update as $update_this_post ):
            $update_this_post->post_title = 'Post Prefix: '.$update_this_post->post_title;//The post field you are updating.
            wp_update_post( $update_this_post );
        endforeach;

Replace ‘x’ with the ID of the category you’d like to update. ’1000′ is the number of posts we’d like to update; change it to what works for you

Using this technique, you can update any field (post title, authors, category, etc) of your posts in bulk at a go. Modify the code above to suit your needs by changing:

1. The get_posts

This is what determines which posts you’d like to update in bulk. In the example above, we targeted posts in a category with ID x (cat=x) and we restricted it to the first 1000 posts (&showposts=1000). Change this according to which posts you’d like to update. A full list of parameters you can use and a few examples are shown here

e.g. to target posts by author ‘user_nicename‘:

$posts_to_update  = new get_posts( 'author_name=kakoma' );

More on get_posts() here: get_posts() details

2. The $post_update_array

This is the next bit you’ll need to update. Change this to match what field you’d like to update. In the case above, we are updating post titles so we modify $update_this_post>post_title by adding ‘Post Prefix’ to the current title. You can modify content, author, etc in the same way. All you need to know is the field name.

e.g. To modify your content instead, replace:

$update_this_post->post_title

with

$update_this_post->post_content = $update_this_post->post_content.' Awesome suffix added to every post';

For a full list of the fields you can modify, check here

Changes to code are done. On to…

Where to put the code

There are very many places this code can be put. In functions.php in your theme, in a plugin, in a template…putting it in a plugin though is the most appropriate way of doing things. To do this, we’ll need to add a bit more code above the lines we’ve discussed. Use this:

<?php
/**
  * Plugin Name:       Post Bulk Update
  * Description:       On activation, I'll updates certain fields of your posts at once. Can't wait!
  * Version:           1.0.0
  * Author:            Your name here
  * License:           GPL-2.0+
  * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
  *  */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly 

if ( ! class_exists( 'MyPlugin_BulkUpdatePosts' ) ) : 

class MyPlugin_BulkUpdatePosts {          

public function __construct(){
      register_activation_hook( __FILE__, array( $this, 'do_post_bulk_update' ) );//Run this code only on activation
}          

//Put your code in this function
public function do_post_bulk_update(){
    $posts_to_update = get_posts('cat=x&showposts=1000');//Retrieve the posts you are targeting
    foreach ( $posts_to_update as $update_this_post ):
           $update_this_post->post_title = 'Post Prefix: '.$update_this_post->post_title;//The post field you are updating.
           wp_update_post( $update_this_post );
    endforeach;
 }

}
endif;

return new MyPlugin_BulkUpdatePosts();

Put this code in a file (e.g. post_bulk_update.php), put that file in a folder, zip that folder and upload it as a plugin (Instructions here). You’ll see a plugin named ‘Post Bulk Update’. On activating the plugin, your changes will be made. Delete the plugin after use.

Let me know if you run into any issues….or if it works for you.

Using diligent minions, I bring these tutorials & tips to your inbox every week. Give a minion work today; add your email address here

  • pilda

    This plugin duplicate all my post 🙁 Am I doing it wrong?

    • kakoma

      Hi Pilda,
      I’m not sure. Could you share your code? Here or on http://pastebin.com/

      • kakoma

        Didn’t quite hear from you again @pilda. The code’s been updated though

  • Aurelijus Useckas

    bullshit code, just makes fkin duplicates.

    • kakoma

      Hey @aurelijususeckas:disqus , thanks for the feedback. Sorry for running into that; I re-tested and realised that because of the hook we were using (init), if you activated the plugin and visited any other page (say the posts screen, to check if the code worked), the code would run again.

      I’ve switched the code to run only when the plugin is activated and it’s working perfectly. Thanks

  • Tiago Góes

    how can I view the posts in an iframe and then updates them? I need to open the post because it performs a javascript code that updates the permalink

    • kakoma

      Hi @tiagoges:disqus, why are you using javascript code to update the permalink? The permalinks used are uniform across all the posts. Is updating them from settings > Permalinks not an option? https://codex.wordpress.org/Using_Permalinks

  • Pingback: [ASK] wordpress - Force update all posts in custom post type, no content changes | Some Piece of Information()

  • Pingback: Force update all posts in custom post type, no content changes | Question and Answer()

  • Muneer

    What if I want add some text to the content in middle or at the end of the post?

    • kakoma

      Hi @MuneerShaik:disqus , to add text to the end of the post, chane the part that reads:

      $update_this_post->post_title = ‘Post Prefix: ‘.$update_this_post->post_title;

      to :

      $update_this_post->post_content = $update_this_post->post_content.’Whatever you want to add at the end’;

      Adding content to the middle would generally require that you first split the content into two – a before and an after and then add your content to one of the sections. This can be done in several ways – using explode or preg_replace for example. Or, even using a string count of some sort. For something like this, the final implementation really comes down to what marks ‘the middle’ of your content

  • Arijit Biswas

    Does the code still works?

    • kakoma

      @iarijitbiswas:disqus, yes it does.

      • Arijit Biswas

        Hi, I just want to update the post, I don’t wants to add anything or change anything.. all I want is, hit update.
        How can I achive that?

        • kakoma

          What do you want to update @iarijitbiswas:disqus ? I can’t propose anything useful till I get a better understanding of what you want to do. There’s also the option of manually editing and updating the post(s) from the WP dashboard

          • Arijit Biswas

            I knew you wouldn’t understand. 😛
            I actually update all of my 5k posts, I don’t wants to add anything or change anything.
            Technically change the modified date of all posts to the current date for CTR sake. 😉

          • kakoma

            To change the modified date for each of the posts, change the line that reads:
            $update_this_post->post_title = 'Post Prefix: '.$update_this_post->post_title;//The post field you are updating.

            to something like

            $update_this_post->post_modified = //put new date here;
            $update_this_post->post_modified_gmt = //put new date here;

            For 5k posts, you might want to first test this on a much smaller subset before attempting to run it on all of them. Also, based on your tests, when finally doing the update, you could run this on a smaller subset of the posts at a time – say 1k at a go (depending on your PC’s resources)

          • Arijit Biswas

            What is the date format? & How can set the to the current time?

          • kakoma

            The date format is date("Y-m-d H:i:s")
            You can set it to the current time using:


            $update_this_post->post_modified = date("Y-m-d H:i:s");

          • Arijit Biswas

            Should I use the same value to the post_modified_gmt?

          • kakoma

            Actually, use this instead:

            $update_this_post->post_modified =current_time( 'mysql' );
            There’s no need for post_modified_gmt; WP will auto-populate that

          • Arijit Biswas

            The previous code you shared, did worked for me.
            Mind if I ask what’s difference between the previous one and this one?
            It’s saves the date to MySQL server?

          • kakoma

            Glad it worked. Both versions work; this last one uses a WP function, current_time, instead of directly making the call to date, which the first version does

          • Arijit Biswas

            Both works. Thank you so much. You’re awesome. 🙂

          • kakoma

            You are welcome! I write about other WP tips and tricks so do subscribe if you are into WP development

          • Arijit Biswas

            Doing unlimited posts makes my server crash, seems I have to do it in batch.

          • kakoma

            I’d have been very surprised if you’d have done all 5k at a go; do batches

          • Arijit Biswas

            Tried to do a 100 batch, but still crashing, 503 Service Unavailable.
            I’m using DigitalOcean+ServerPilot. 512mb ram. 256mb php memory limit.
            It shouldn’t crash. Any clue?

          • kakoma

            Given what you are working with, it’s much easier and less resource intensive for you to do this update directly in the database. Login to MySQL and run:
            update wp_posts set post_modified = $date where //the condition
            Replace $date with the current date at the time of running it and use the appropriate where condition depending on what you are looking for

          • Arijit Biswas

            I found that a long time ago, in stackoverflow, but I had know idea that was a SQL query. :p

            I’m using NOW() to get the current time


            UPDATE wp_posts SET post_modified=NOW();

            Worked like a charm. 🙂

          • kakoma

            I’m glad it all fell in place finally. Good stuff

          • Arijit Biswas

            No man!
            It works, but the SQL query does not update the sitemap.xml modified time, so Search Engines would not know that my post has been updated. 🙁

          • kakoma

            Sorry man. You might have to look around for something else for that. This wouldn’t address that

          • Arijit Biswas

            It does not update the sitemap.xml modified time:(
            I also wants to notify that, my post has been updated.