WP_Query issues with sortby

May 2nd, 2008 Mark

Was trying to figure out the proper way to sort my WP_Query post results by category and found out that there are some buggy things with the sortby using WP_Query. I wanted to sort by cat_name then tried cat_id and cat_nicename. All work for the most part but would throw a post randomly out of order. So I ended up stacking my results into an object array and using the trusty PHP “sort”. Like this:

class an_object {
var $an_name;
var $an_slug;
}

$i=0;
$my_query = new WP_Query();
while ($my_query->have_posts()) : $my_query->the_post();
$an[$i] = new an_object();
foreach((get_the_category()) as $category) {
$an[$i]->an_slug = $category->category_nicename;
$an[$i]->an_name = $category->cat_name;
}
$i++;
endwhile;

sort($an);

$z=0;
while($an[$z]){
echo $an[$z]->an_name.” “.$an[$z]->an_slug.”<br />”;

$z++;
}