I am in the process of importing large amounts of data into a custom post type that has several custom fields (postmeta fields created by Advanced Custom Fields). I am using the following function to import the data and it works fine with my test file of about 10 posts with the exception of the postmeta. Here is the function I am using for the import:
function mysite_import_json() {
$json_feed = 'http://local.mysite.com/wp-content/test.json';
$json = file_get_contents( $json_feed );
$objs = json_decode( $json, true );
$wp_error = true;
$post_id = - 1;
foreach ( $objs as $obj ) {
$title = $obj['title'];
$meta1 = $obj['taxonomy'][0];
$meta2 = $obj['nom'];
$meta3 = $obj['prenom'];
$d = new DateTime();
$d->setTimestamp( $obj['created'] );
$date_created = $d->format( 'Y-m-d H:i:s' );
$post_meta = array(
'meta_1' => $meta1,
'meta_2' => $meta2,
'meta_3' => $meta3,
);
$post_data = array(
'post_title' => $title,
'post_date' => $date_created,
'post_status' => 'publish',
'post_type' => 'cpt',
'meta_input' => $post_meta,
);
if ( null === get_page_by_title( $title, 'object', 'message' ) ) {
$post_id = wp_insert_post( $post_data, $wp_error );
foreach ( $post_meta as $key => $value ) {
update_field( $key, $value, $post_id );
}
} else {
$post_id = - 2;
}
}
}
add_action( 'after_setup_theme', 'mysite_import_json' );
The post meta is indeed imported but I have to manually click the update button in order to display the data on the front-end. I researched this a bit and found this (below, I would link the article but I've lost it) which I tried and limited the number of posts to 10 to rule out memory problems but it still doesn't have the desired effect of reproducing the click on publish button.
function mass_update_posts() {
$args = array(
'post_type' => 'message',
'posts_per_page' => 10
);
$my_posts = get_posts( $args );
foreach ( $my_posts as $key => $my_post ) {
$meta_values = get_post_meta( $my_post->ID );
foreach ( $meta_values as $meta_key => $meta_value ) {
update_field( $meta_key, $meta_value[0], $my_post->ID );
}
}
}
add_action( 'init', 'mass_update_posts' );
I am also aware that this is going to be expensive memory-wise and am not sure the best way to go about this. Maybe in batches?
EDIT: I should mention that the data is displayed on the front end by way of the WP API which actually seems to be the issue. So I suppose I need to update the API rather that the post meta in the database. The plugin that displays the ACF meta data for the WP API is ACF to WP-API.