对WP_Query进行排序(ussort)


sort (usort) on WP_Query

无论如何都不能使它运行:

$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(); 

在不调用sort的情况下,一切都工作得很好。我真的需要在查询后运行一个自定义排序。

注意usort()只返回truefalse,所以用这一行:

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

您正在重写帖子。改为:

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

我想知道为什么你必须使用usort而不是WP_Queryposts_orderby过滤器的orderby参数。