SimplePie 1.5 is now available!

SimplePie Documentation.  Learn how to use this thing.  It's way better than going to school.

You are here: Documentation » Tips, Tricks, Tutorials, and Screencasts » Sorting by custom criteria instead of date

Sorting by custom criteria instead of date

Sometimes you may want to sort items by custom criteria other than the time/date. In the following example, we're going to sort the Digg feed by the number of diggs instead of by date.

:!: This tutorial assumes that you're already familiar with using SimplePie, including looping through items. It also assumes that you know how to use SimplePie Add-ons (specifically the Digg RSS Add-on).


  • Supported in SimplePie 1.0.
  • Code in this tutorial should be compatible with PHP 4.3 or newer, and should not use PHP short tags, in order to support the largest number of PHP installations.


In this example, we'll use the methods available in the Digg RSS Add-on to grab extra Digg-specific data, and we'll extend the SimplePie class and override the sort_items() method to sort by number of diggs.

// Include the necessary libraries. Digg Add-on found at
// Extend the SimplePie class and override the existing sort_items() function with our own.
class SimplePie_Custom_Sort extends SimplePie
	public static function sort_items($a, $b)
		return $a->get_digg_count() <= $b->get_digg_count();
// Instantiate a new SimplePie_Custom_Sort class.
$feed = new SimplePie_Custom_Sort();
$feed->set_item_class('SimplePie_Item_Digg'); // Make sure we use the Digg Add-on
$feed->set_cache_duration(300); // 5 minutes
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	<meta http-equiv="Content-type" content="text/html; charset=utf-8">
	<title>Digg Test</title>
	<style type="text/css">
	body {
		font:1em/1.3em "Lucida Grande";
	h2 span.diggs {
	<?php foreach ($feed->get_items() as $item): ?>
		<h2><span class="diggs"><?php echo $item->get_digg_count(); ?></span> <a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h2>
		<p><?php echo $item->get_description(); ?></p>
		<p><small>Posted by <a href="<?php echo $item->get_submitter_username(); ?>"><?php echo $item->get_submitter_username(); ?></a> on <?php echo $item->get_date(); ?></small></p>
	<?php endforeach; ?>

tutorial/sorting_by_custom_criteria_instead_of_date.txt · Last modified: 2013/08/11 04:58 (external edit)