Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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