Return to Snippet

Revision: 52143
at October 14, 2011 11:47 by kingkool68


Initial Code
<?php
$args = array(
	'numberposts' => -1,
	'orderby' => 'title',
	'order' => 'ASC'
);

$posts = array();
foreach( get_posts($args) as $post ):
	$terms = array();
	foreach(wp_get_object_terms( $post->ID, array('taxonomy1', 'taxonomy2') ) as $term) {
		//Works if there is only one term tagged in the post for this taxonomy. You need to figure out how best to handle multiple terms. You might try imploding() them in a comma seperated list: "Term 1, Term 2"
		$post[$term->taxonomy] = $term->name;
	}
	$posts[] = (object) $post;
endforeach;

/**
* Sort array of objects by field.
*
* @param array $objects Array of objects to sort.
* @param string $on Name of field.
* @param string $order (ASC|DESC)
**/
    function sort_on_field(&$objects, $on, $order = 'ASC') {
        $comparer = ($order === 'DESC')
            ? "return -strcasecmp(\$a->{$on},\$b->{$on});"
            : "return strcasecmp(\$a->{$on},\$b->{$on});";
        usort($objects, create_function('$a,$b', $comparer));
    }
/*
Use `strcmp` for case-sensitive string comparing.
Use `strcasecmp` for case-insensitive string comparing.

Source: http://www.php.net/manual/de/function.usort.php#104873
*/

sort_on_field($posts, 'taxonomy1', 'DESC');

foreach( $posts as $post ) {
	echo $post->taxonomy1;
}
?>

Initial URL

                                

Initial Description
1. Get Posts however you see fit
2. Loop through the posts getting the terms from taxonomies and add them to the Post object
3. Sort the Array of Post Objects by the property you want them sorted by using sort_on_field()

Initial Title
[WordPress] Get Posts By Term and Sort Them

Initial Tags
php, sort, object, wordpress

Initial Language
PHP