Programmatic Post Creation and Updates in WordPress with wp_insert_post and wp_update_post

Create and update posts in code with wp_insert_post()

wp_insert_post() and wp_update_post() create and change posts without the editor: in import scripts, WP-CLI commands, plugin activation (a default page), or a cron job that pulls content from an API. They take an array with the columns of the posts table and two helpers, meta_input and tax_input, that save meta and terms in the same call.

Problem: An import must create posts from external data with meta and categories, and running it again must update the posts it created before instead of making duplicates.

Solution: Store the external ID in post meta, look it up before inserting, and call wp_update_post() with the found ID or wp_insert_post() for a new post, both with true as the second argument to get a WP_Error on failure. Assign terms with wp_set_object_terms() after the insert.

Insert or update

<?php
function ha_upsert_post( array $data ) {
    $source_id = sanitize_text_field( $data['source_id'] );

    $existing = get_posts( array(
        'post_type'      => 'post',
        'post_status'    => 'any',
        'meta_key'       => '_ha_source_id',
        'meta_value'     => $source_id,
        'posts_per_page' => 1,
        'fields'         => 'ids',
    ) );

    $postarr = array(
        'post_type'    => 'post',
        'post_status'  => 'publish',
        'post_title'   => sanitize_text_field( $data['title'] ),
        'post_content' => wp_kses_post( $data['content'] ),
        'post_author'  => 1,
        'meta_input'   => array(
            '_ha_source_id'  => $source_id,
            '_ha_source_url' => esc_url_raw( $data['url'] ),
        ),
    );

    if ( ! empty( $data['date'] ) ) {
        $postarr['post_date'] = gmdate( 'Y-m-d H:i:s', strtotime( $data['date'] ) ); // in the site's time zone
    }

    if ( $existing ) {
        $postarr['ID'] = $existing[0];
        $post_id       = wp_update_post( wp_slash( $postarr ), true );
    } else {
        $post_id = wp_insert_post( wp_slash( $postarr ), true );
    }

    if ( is_wp_error( $post_id ) ) {
        return $post_id;
    }

    if ( ! empty( $data['categories'] ) ) {
        wp_set_object_terms( $post_id, array_map( 'intval', $data['categories'] ), 'category' );
    }

    if ( ! empty( $data['tags'] ) ) {
        wp_set_object_terms( $post_id, $data['tags'], 'post_tag' ); // names or slugs, missing tags are created
    }

    return $post_id;
}

wp_slash() is needed because both functions expect slashed data, like it comes from a form; without it, backslashes in the content disappear. meta_input calls update_post_meta() for each key.

Why not tax_input

tax_input works only if the current user may assign terms of that taxonomy. In WP-CLI and cron there is no current user, and the terms are silently not assigned. wp_set_object_terms() does not check capabilities, which is what an import needs. Note that for categories it expects term IDs as integers: a numeric string like “7” is treated as a name and creates a new category called “7”.

Large imports

<?php
wp_defer_term_counting( true );   // update term counts once at the end
wp_suspend_cache_invalidation( true );

foreach ( $rows as $row ) {
    $result = ha_upsert_post( $row );
    if ( is_wp_error( $result ) ) {
        error_log( 'Import ' . $row['source_id'] . ': ' . $result->get_error_message() );
    }
}

wp_suspend_cache_invalidation( false );
wp_defer_term_counting( false );

Every insert fires save_post and the status transition hooks, so plugins that do heavy work on them (sending notifications, pinging search engines, generating images) run for every imported post. Run large imports from WP-CLI, in batches, and deactivate such plugins during the import if needed.

NOTE: post_date is the local time of the site, post_date_gmt the UTC time. If you set only post_date, WordPress calculates the GMT date from the site’s time zone. A date in the future with the status publish turns the post into a scheduled one (future).