WordPress – How to iterate through all posts to apply update

The following WordPress PHP function will load when the wp-admin is opened, and iterate through each post.

This can be helpful if you need to retrospectively iterate through all existing posts – for example, to apply changes to article tags.

IMPORTANT: remove, or comment out, code after it’s run – this may use a lot of system resources to run if you have a lot of posts.

If you’re not sure where to place this code I highly recommend you read How to create a WordPress plugin for your custom functions.

function update_all_posts() {
     if ( !is_admin() ) return; // only run on admin page

     $args = array(
         'post_type' => 'posts',
         'numberposts' => -1
     );

     $posts = get_posts( $args );

     foreach ( $posts as $post ){
         // do something here for each $post
     }
}

add_action( 'wp_loaded', 'update_all_posts' );