Con
Yet another WordPress dev

Saving posts programmatically after an import

I recently did a bulk post import for one of my sites and noticed that the related articles did not get set. Upon inspecting I found that saving the post manually in the backend did also set the related posts as desired. So I wrote some code to get posts by custom taxonomy and then auto save them all:

<?php

// Get all posts by custom taxonomy

$a = get_posts(array(
    'showposts' => -1, // you can try and test run this by setting a pagination value of higher than 1. 
    'post_type' => 'post',
    'tax_query' => array(
        array(
        'taxonomy' => 'taxonomy-name',
        'field' => 'name',
        'terms' => array('taxonomy-slug'))
    ),
    'orderby' => 'ID',
    'order' => 'ASC')
);

$posts = array();

// Generate array of post IDs
 
foreach ( $a as $post ) {
   $posts[] += $post->ID;
}

// Feed post array into wp_update_post

foreach ( $posts as $post_id ) {

$arg = array(
    'ID'            => $post_id,
);
wp_update_post( $arg );

}

I suggest using WP Console to run this code – this external post explains how it works. Hope this helps you save some time the next time you need to autosave posts. If you are looking for something to automatically save all products here is a mini plugin of mine that will do just that.

keep reading?

Leave the first comment