Question

I have been struggling to import posts from an some json data. The problem is that wp_insert_post() is adding multiple versions of the posts. I was previously checking if the post existed by checking if the title existed but there are several posts to be imported that have the same title but different content.

function get_all_cpt_ids() {
    global $wpdb;
    $mids = $wpdb->get_results( "SELECT ID FROM tablename.subsite_4_posts WHERE post_type='thing'", OBJECT );

foreach ( $mids as $key => $value ) {
    $thing_ids[] = $value->ID;
}

    return $thing_ids;
}

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;
  $id_arr    = [];

foreach ( $objs as $obj ) {
    $id_arr    = get_all_cpt_ids();
    $id        = $obj['nid'];
    $title     = $obj['title'];
    $meta1     = $obj['name'];
    $d         = new DateTime();
    $d->setTimestamp( $obj['created'] );
    $date_created = $d->format( 'Y-m-d H:i:s' );
    $post_meta = array(
        'meta_1'        => $meta1,
    );

    $post_data = array(
        'import_id'   => $id,
        'post_title'  => $title,
        'post_date'   => $date_created,
        'post_status' => 'publish',
        'post_type'   => 'thing',
        'meta_input'  => $post_meta,
    );

    if ( ! in_array( $id_arr, $id, true ) ) {
        $post_id = wp_insert_post( $post_data, $wp_error );

        foreach ( $field_meta as $key => $value ) {
            update_post_meta( $post_id, $key, $value );
        }
    } 
  }
}

add_action( 'after_setup_theme', 'mysite_import_json' );

As an aside I am doing this all locally so I'm not worried about security when querying the database.

I also set the function to run only once by adding a flag as an option once it has run so I don't really understand why wp_insert_post() is running more than once per $obj in the foreach loop.

Was it helpful?

Solution

The problem ended up being the hook after_setup_theme. I was effectively invoking the function by refreshing the browser which launches the hook in both Javascript and PHP so the hook was being triggered more than once when the browser was refreshed.

Once I disabled Javascript everything worked fine. Another solution would have been to use a different hook that is only triggered once.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top