sort (usort) on WP_Query

时间:2015-07-28 23:24:17

标签: php wordpress wp-query usort

Can't seem to get this running no matter what:

$args = array(...);
$unitsQuery = new WP_Query($args);

function customCompare($a, $b)
{
    return strcasecmp($a->post_title,$b->post_title);
}

$unitsQuery->posts = usort($unitsQuery->posts, 'customCompare');

if( $unitsQuery->have_posts() ) {
    while($unitsQuery->have_posts()) : $unitsQuery->the_post();?>

    <div><?php the_title(); ?></div>

    <?php endwhile;
}
wp_reset_postdata(); 

Everything works absolutely fine without calling the sort. I REALLY need to run a custom sort after the query.

1 个答案:

答案 0 :(得分:2)

Note that Select * from ( SELECT TOP 3 b.BannerID, b.BannerWeight FROM Banners b ORDER BY NEWID() ) a order by a.bannerweight only returns usort() or true, so with this line:

false

you're overriding the posts. Change it to:

$unitsQuery->posts = usort($unitsQuery->posts, 'customCompare');

I wonder why you must use usort( $unitsQuery->posts, 'customCompare' ); instead of the usort parameter of orderby or the WP_Query filter.