The RSS feed has all the items in a fixed order(latest to oldest). In this case you can save the date & time of the last post you created, as an option & when you read the feed again, you can check the time previously saved to know which of the posts in the feed are new & insert them, then update the time again
The functions you’re interested in are update_option
, get_option
& wp_insert_post
. You can find the reference for each of them in the wordpress codex, just google it. The flow would go like this
// retrieve the previous date from database
$time = get_option('mylastfeeddate');
// include the code to read the xml file here &
// then the foreach loop as you did in the question
foreach($items as $item) {
// if the date is < than the date we have in database, get out of the loop
if( $item->pubDate < $time) break;
// assign the values in the format of wp_insert_post()
$out = array();
// insert the post
$post_id = wp_insert_post( $out );
}
// update the new date in database to the date of the first item in the loop
update_option( 'mylastfeeddate', $items[0]->pubDate );
UPDATE
For making the code execute after some fixed time frame use wordpress cron functions like this
if (!wp_next_scheduled('update_feed'))
wp_schedule_event(current_time('timestamp'), 'hourly', 'update_feed');
add_action('update_feed', 'function_name');
function function_name() {
// here goes all the code to read the feed
}
change hourly
to the time you like here is the codex reference http://codex.wordpress.org/Function_Reference/wp_schedule_event
For adding custom time frames
add_filter('cron_schedules', 'new_cron_schedules');
function new_cron_schedules($schedules) {
array_merge($schedules, array('two_hourly' => array( 'interval' => 7200, 'display' => __('Twice Hourly') )));
}
After this filter for eg. you can replace ‘hourly’ above to ‘two_hourly’