I have stucked in writing a simple function that on certain page update refresh all posts in a custom post type.
Here is my code (based on this):
add_action('save_post', 'bulk_refresh');
function bulk_refresh($post_id) {
if($post_id != 123)//123 is the 'certain page' id
return;
$posts_to_update = new WP_Query(array('post_type' => 'MY_CUSTOM_TYPE', 'posts_per_page' => -1));
while($posts_to_update ->have_posts()) : $posts_to_update ->the_post();
$args = array( 'ID' => $post->ID );
wp_update_post( $args );
endwhile;
// Reset Post Data
wp_reset_postdata();
}
On first sight all must be working fine, but when I save the page with id ‘123’ all posts in the custom post type are duplicated. I want just to ‘refresh’ them.
Any ideas where I am wrong?
Ah, I found the answer myself. I’ve added global $post before the loop and now all seems to works fine. I don’t know if this is a good practice, so if you have another ideas share them 🙂
Here is the revised code: