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

      • david

        Hi Kakoma,
        Been searching for something like this for a while.
        I want to insert the shortcode: [chosen] into all custom posts called ‘plant’ – (to format a select dropdown list).
        I’ve update this line:

        $update_this_post-&gt;post_content = $update_this_post-&gt;post_content.'[chosen]';
        

        How should:

        $posts_to_update = get_posts('cat=x&amp;showposts=1000');
        

        be change to update all ‘plant’ custom posts.

        Thanks for your help
        David

        • david

          Would this work?
          $args = array(
          ‘post_title’ => ‘Coffea Arabica L.’,
          ‘post_type’ => ‘plant’
          );
          public function do_post_bulk_update(){
          $posts_to_update = get_posts($args);

          This is to test 1 post, for all plant custom posts I’d remove post_title.

          Thanks
          David

  • 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

          • borsaegypt2

            hi guys … all codes is working well for modified date … but how
            to make a patch every 100 posts for example as i have a huge data base
            … also can i run it for all posts not only for one category per time ?

            regards 🙂

          • kakoma

            Hi @borsaegypt2:disqus
            Yes, you can run this for all posts. Test it first though. To run it on all posts, remove the `cat` restriction so you remain with just `showposts=1000`.

            To patch just 100 posts at a time, change `showposts=1000` to `showposts=100`

          • borsaegypt2

            Thank you Kakoma so much for your replay … 🙂

            but this will make the same last 100 posts every time as i understand ?

            also what about this as it make the function run for every number of posts and stop for some seconds then run:

            setInterval(function(){
            // method to be executed;
            },5000); // run every 5 seconds

            i’m not sure of the code if it correct or how to input it as a friend sent me it and i’m beginner also 😀

            so could you please advice how to arrange this … i talk about more than 250K posts :/

            sorry for talking long … waiting for you 🙂

            BEST Regards.

          • kakoma

            @borsaegypt2:disqus yes, without any condition, it’d only update the last 100 posts. The code you’ve displayed to run every 5 seconds is JavaScript; it won’t work with this code here.

            If you are dealing with more than 250k posts, you should definitely first backup your database and then do that update on the command line, not using code like this. I recommend you go through these lessons to get started with the MySQL command line: https://code.tutsplus.com/articles/sql-for-beginners–net-8200

          • borsaegypt2

            Thank you so much kakoma for your replay and help … much appreciated … i’ll try and tell you 🙂

          • kakoma

            You are welcome

          • Arijit Biswas

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

  • besties

    Hi thanks for the code.
    How to do batches update?
    Let’s say i want to update per 100 posts, so if i reactivated the plugin, will it only updates the same 100 posts?

    • kakoma

      Hi @besties, the code was written with a single batch of posts in mind so yes, whenever you activate, it will only update the same 100 posts.

      There’s a special case where this won’t happen; this is if the 100 they no longer qualify in the query. e.g. If your query updates all posts with status=’publish’ and your update command on those posts changes that status to say ‘draft’, then the next activation will get the next 100. Is this clear?

  • Vilo

    Is the code working on the latest wp version?

    I run it on the latest wp version but i got this error message:

    “The plugin generated 257 characters of unexpected output
    during activation. If you notice “headers already sent” messages,
    problems with syndication feeds or other issues, try deactivating or
    removing this plugin.”

    • kakoma

      Hi @Vilo, it should work. Could you share your plugin code? You can create a gist on Github https://gist.github.com/

  • Dany

    Hello @Kakoma. I very much appreciate your enthusiasm. I want to update all my posts without changing the post content. The reason I do this is because I use a “Feature Image From URL” plugin. To work I need to “update” all my posts. Hope you help me. Thank you

    • kakoma

      Hi @Dany,
      Thank you. From your description, updating the featured image for all posts using the Featured Image from URL plugin (https://wordpress.org/plugins/featured-image-from-url/) would most likely require that in the bulk update code, you update each post’s meta data. Let me know if you need further instructions in getting this set up