-
-
Save azhar04/8011fd82b6b8a0d77248 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment