1

I hope you all are doing well.

I need to ask something, I tried searching for this but unable to get any relevant answer. I have a JSON feed and using that feed I want to create posts and want to sync/updated those posts whenever JSON feeds changes. Please guide me in this regards.

I know how to create post with JSON feed but don't know how to keep posts sync with that JSON feed.

What I want to achieve using that feed is:
a. If post doesn't exists in Wordpress DB then add it
b. If post exists in Wordpress DB then update it

Updated

One more question I need to ask, what if JSON changes and the item in wordpress post is not available in that updated JSON, in simple words I also want to delete all the items available in posts that previously available in JSON but after JSON changes it's not there.

Thanks,
Neil Bannet

  • wp_insert_post() does exactly that: if the passed post ID exists, the post is updated; otherwise a post is created. What problems exactly do you have to do it? – cybmeta Jan 9 '17 at 11:47
  • Thanks @cybmeta for the reply, please view the question I have added a new line. Please reply for that too. – Neil Bannet Jan 10 '17 at 15:47
1

The important step is to assign a unique ID to every item you get from the source. Hopefully the JSON feed already includes one, but otherwise you will have to somehow create one yourself based on the JSON content.

Once you have the value, you store it as a meta value of the post being created. The code should look something like this

$json = get_json_item();
$uuid = get_json_uuid($json);
// check if exist based on the json_uuid meta
$t = get_posts(array('meta_key' => 'json_uuid', 'meta_value' => $uuid));
if (count($t) == 0) { // create new post
  $pid = wp_insert_post(values extracted from $json);
  update_post_meta($pid,'json_uuid',$uuid);
} else { // post exist
  wp_insert_post(array('ID' => $p[0]->ID,values extracted from $json));
}
  • Thanks for the reply @mark-kaplun , please view the question I have added a new line. Please reply for that too. – – Neil Bannet Jan 10 '17 at 15:51

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.