Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayflores/e8f9cfb92f2509c7164e635b3ec0b4ce to your computer and use it in GitHub Desktop.
Save rayflores/e8f9cfb92f2509c7164e635b3ec0b4ce 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;
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment