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?

没有正确的解决方案

许可以下: CC-BY-SA归因
scroll top