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

I am generating posts based on rows from a table on an existing database.

If a row in the database gets updated I will have to update the respective post.

Read More

The proble is that I have to find the post to be able to update it, and I don’t have any suitable key for that… One chance would be using the title, but the title can change so that is not an option. The best option for me looks like storing the key, from the respective database row, in the wordpress post (not as post id because that can lead to other problems). What is the best way to achieve this? Is there already an auxiliary field for this?

Related posts

Leave a Reply

1 comment

  1. 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.