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 have an XML feed url I am now using this code to create new Custom Post Type Posts from an rss feed in my functions.php file:

    /*
| -------------------------------------------------------------------
| Schedule and update fashion news with the news rss feed
| -------------------------------------------------------------------
| 
| */

if (!wp_next_scheduled('update_feed'))
    wp_schedule_event(current_time('timestamp'), 'hourly', 'update_feed');

add_action('update_feed', 'update_fashion_news');

function update_fashion_news() {
    // retrieve the previous date from database
        $time = get_option('latestpostdate');

        //read the feed
        if(function_exists('fetch_feed')){
            $uri = 'http://www.sitename.com/feed.xml';
            $feed = fetch_feed($uri);
        }

        if($feed) {

            foreach ($feed->get_items() as $item){
                $titlepost = $item->get_title();
                $content = $item->get_content();
                $description = $item->get_description();
                $itemdate = $item->get_date();
                $media_group = $item->get_item_tags('', 'enclosure');
                $img = $media_group[0]['attribs']['']['url'];
                $width = $media_group[0]['attribs']['']['width'];           
                // $latestItemDate = $feed->get_item()->get_date();


                // if the date is < than the date we have in database, get out of the loop
                if( $itemdate <= $time) break;


                // prepare values for inserting

                $post_information = array(
                    'post_title' => $titlepost,
                    'post_content' => $description,
                    'post_type' => 'fashionnews',
                    'post_status' => 'publish',
                    'post_date' => date('Y-m-d H:i:s')
                );

                wp_insert_post( $post_information );    

            }
        }
        // update the new date in database to the date of the first item in the loop        
        update_option( 'latestpostdate', $feed->get_item()->get_date() );
}

[UPDATE: Have updated the code above to move from simple_xml to using simplepie]

[UPDATE2: Have moved the code and wrapped it in a WP schedule event as advised by @Mridul below]

I am still checking to see if my code works when the next batch of news updates arrive. Does anyone think this code wouldn't work for some reason?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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'

share|improve this answer
    
Good idea! I was thinking of checking if post title exists in database and then inserting the post. Can you tell me how I can 'save the date & time of the last post you created, as an option'? –  Amit Erandole Oct 17 '12 at 18:26
1  
updated the answer above with more details –  Mridul Aggarwal Oct 17 '12 at 18:52
1  
one reason i can think of for malfunction is that the first time you run this code there's no date value saved in the database(get_option returns null). Also you should do a check for $feed just before foreach, in case $feed isn't initialised or if there are 0 items –  Mridul Aggarwal Oct 18 '12 at 8:25
1  
updated the answer –  Mridul Aggarwal Oct 18 '12 at 8:59
1  
i couldn't see any error in it, but still keep an eye out just in case. Also the event is scheduled only after the wp_schedule_event is executed, so you'll have to refresh the page once before the timer gets activated –  Mridul Aggarwal Oct 18 '12 at 9:32
show 7 more comments

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.