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();
}
?>
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 theSimplePie
class, so you have to throw in one URl after each other. In return you get a fully bakedSimplePie object
.Reworked code
So your code should be something like the following:
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 amerge_items()
method. Maybe you can use this one:Now
merge_items()
takes four arguments.$urls
– an array ofSimplePie
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.