2

I have found the following code to import feeds from multiple feeds and show them in wordpress. But, I want to sort all the combined feeds by date and show only 10. How can I do that?

Thanks

<?php
  $feed = fetch_feed(array('http://www.site1.com/feed/', 'http://www.site2.com/feed/'));
foreach($feed->get_items() as $item) {
   echo $item->get_title();
}
?>
1
  • Take a look at WP RSS Aggregator
    – urok93
    Jul 5 '12 at 14:15
1

Checking the arguments

The main problem with your attempt is that you assume the function to take an array of arguments. The point is that this doesn't work. The internals of fetch_feed() Link to source shows you that is simply is a wrapper for the SimplePie class, so you have to throw in one URl after each other. In return you get a fully baked SimplePie object.

Reworked code

So your code should be something like the following:

$feeds[] = fetch_feed( 'http://site-a.example.com/feed/' );
$feeds[] = fetch_feed( 'http://site-b.example.com/feed/' );
foreach( $feeds as $feed )
{
    foreach ( $feed->get_items() as $item )
    {
        echo $item->get_title();
    }
}

The solution

The kool thing with this is, that you can (as your code already shows) then use the classes methods. I'm no expert with SimplePie (nor have I even used this class), but from looking at the source, there seems to be a merge_items() method. Maybe you can use this one:

$simple_pie = new SimplePie;
$feeds[] = fetch_feed( 'http://site-a.example.com/feed/' );
$feeds[] = fetch_feed( 'http://site-b.example.com/feed/' );
$feed_posts = $simple_pie->merge_items( $feeds, 0, 10, 10 );

Now merge_items() takes four arguments.

  • $urls - an array of SimplePie objects (that's why we fetched the feed in the first place)
  • $start
  • $end
  • $limit

Internally the method calls get_items() - the exact same you've done. And both methods call a sort callback method that sorts by date.

Task done.

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.