Question

I am building a function in wordpress that reads an XML file and imports 100-500 events as a post type to wordpress. The events have a lot of meta data that is saved as post meta. One of the meta data items will be a unique (string) identifier from each event in the XML feed.

The importer will be set up as a wp_cron, to make sure that our database is up to date.

In order to make sure that i dont add duplicates every time the import runs, I would like to check if a post with the unique identifier already exists -- if it does it will update, otherwise insert.

This is how the wp_insert_post function works with the post id's. If a post with the specified ID already exists, it will update instead of inserting.

How can I best achieve this? Can I run a get_posts() with a meta query on every entry? Will that be efficient or expensive performance wise? Would it result in to many sql queries?

Any advice on how to do this check would be much appreciated.

Was it helpful?

Solution

You can choose between simplicity and efficiency.

Running a get_posts() with a meta query for every entry is the simplest approach, and will do the job. Of course, as you pointed out, there are performance considerations.

If you are looking for a more efficient solution, you will have to dive as deep as the database layer and run your own SELECT query. Then, store the results in an associative array and check every entry against that.

Something like the following:

global $wpdb; // if we're in a function
$q="
  SELECT $wpdb->posts.ID,$wpdb->postmeta.meta_value
  FROM $wpdb->posts 
  JOIN $wpdb->postmeta ON ($wpdb->posts.ID=$wpdb->postmeta.post_id)
  WHERE $wpdb->post.post_type='event' and $wpdb->postmeta.meta_name='xml_id'
  ";
$rows=$wpdb->get_results($q,OBJECT);
$events_idx=array();
foreach($rows as $row) $events_idx[$row->meta_value]=$row->ID;

After that, checking if an event already exists is as easy as isset($events_idx[$xml_id]). And if it eventually exists, you would update the post with id given by $post_id=$events_idx[$xml_id].

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top