Created
January 8, 2012 02:24
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
} | |
?> |
Amazing, cheers.
Works great as of 2020 !
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
This is super useful. Thanks.