【问题标题】:sort (usort) on WP_Query对 WP_Query 进行排序(usort)
【发布时间】:2015-07-28 23:24:17
【问题描述】:

无论如何似乎都无法运行:

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

没有调用排序,一切都工作得很好。我真的需要在查询后运行自定义排序。

【问题讨论】:

    标签: php wordpress usort


    【解决方案1】:

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

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

    您正在覆盖帖子。将其更改为:

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

    我想知道为什么你必须使用usort 而不是WP_Queryorderby 参数或posts_orderby 过滤器。

    【讨论】:

    • 感谢 Birgire,现在我明白为什么在分配 $query->posts 后我得到“1”了。原因是我想在排序中使用的数据不在帖子中。这些帖子只有一个分类术语(自定义字段)的指针(id),但我想按术语的字母顺序对帖子进行排序。 (我尽可能使用 wp_query 中的排序,因为它更容易,但不认为这可能)。现在全部排序谢谢!
    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2012-03-04
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多