Skip to content

Instantly share code, notes, and snippets.

@bradyvercher
Created January 8, 2012 02:24
Show Gist options
  • Save bradyvercher/1576900 to your computer and use it in GitHub Desktop.
Save bradyvercher/1576900 to your computer and use it in GitHub Desktop.
WordPress: Sort an array of post objects by any property, remove duplicates, and use post ids as the key in the returned array.
<?php
function sort_posts( $posts, $orderby, $order = 'ASC', $unique = true ) {
if ( ! is_array( $posts ) ) {
return false;
}
usort( $posts, array( new Sort_Posts( $orderby, $order ), 'sort' ) );
// use post ids as the array keys
if ( $unique && count( $posts ) ) {
$posts = array_combine( wp_list_pluck( $posts, 'ID' ), $posts );
}
return $posts;
}
class Sort_Posts {
var $order, $orderby;
function __construct( $orderby, $order ) {
$this->orderby = $orderby;
$this->order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
}
function sort( $a, $b ) {
if ( $a->{$this->orderby} == $b->{$this->orderby} ) {
return 0;
}
if ( $a->{$this->orderby} < $b->{$this->orderby} ) {
return ( 'ASC' == $this->order ) ? -1 : 1;
} else {
return ( 'ASC' == $this->order ) ? 1 : -1;
}
}
}
?>
@vanderwijk
Copy link

For anyone looking to specifically sort WP Post objects, you can also use the WordPress function wp_list_sort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment