How to store an extra (surrogate) ID when creating a post with wp_insert_post?

Concept

As I’ve currently done this, I found the easiest part would be to save the original UID (unique ID) from your “origin”-database as post meta value.

Every time you update a post, you just have to search for a post that has this meta entry. Just make sure that you set the last value to true when you add the post meta entry, as you need to be able to query it.

Code example (rough)

Here’s close to what I did:

$query = new WP_Query( array(
     'post_type'   => '_YOUR_POST_TYPE_'
    ,'post_status' => array(
         'publish'
        ,'future'
        ,'pending'
     )
    ,'meta_query'  => array( array(
         'key'       => '_YOUR_KEY_'
        ,'value'     => '_SEARCHED_ID_'
        ,'compare'   => 'EXISTS'
        ,'type'      => 'NUMERIC'
     ) )
    #,'fields'     => 'ids'
) );

Then you can check $query->found_posts (or was it $query->number_posts?) to see if you got a post. If so, simply go over it and update (or delete) the taxonomy terms, post data and post meta (in case you changed something on your remote source/DB).

In case you just want to check weather the post exists (which means: You’re inserting, but not updating or deleting post data), just uncomment the last line fields in the above WP_Query. This way the query will be faster and you’ll get an ID or an empty array back as result. You can then skip the post (in case of an ID) or insert it (in case of an empty array).

Final Note: You of course, have to replace _YOUR_KEY_, _SEARCHED_ID_ and _YOUR_POST_TYPE_. You also have to pay attention, that you’re saving it as int value, as the NUMERIC type else won’t work.