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.

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?

1 Answer 1



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(
    ,'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.

  • @nsn Then please post it as separate answer … btw, this was marked by you as solution years ago. And asked as well. Did you just stumble upon your own question again or did it take you ~2years to figure that one really out?
    – kaiser
    Feb 25, 2016 at 10:45
  • sorry, I confused with a new question I did (related)
    – nsn
    Feb 25, 2016 at 12:53
  • @nsn no problem
    – kaiser
    Feb 25, 2016 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.