Importing multiple RSS feed into WordPress and sorting them by date

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.