在 WP_Query 上排序 (usort)
sort (usort) on WP_Query
似乎无法得到这个 运行ning 无论如何:
$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();
无需调用排序,一切正常。我真的需要在查询后 运行 自定义排序。
注意 usort()
只有 returns true
或 false
,所以用这一行:
$unitsQuery->posts = usort($unitsQuery->posts, 'customCompare');
您正在覆盖帖子。将其更改为:
usort( $unitsQuery->posts, 'customCompare' );
我想知道为什么您必须使用 usort
而不是 WP_Query
或 posts_orderby
过滤器的 orderby
参数。
似乎无法得到这个 运行ning 无论如何:
$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();
无需调用排序,一切正常。我真的需要在查询后 运行 自定义排序。
注意 usort()
只有 returns true
或 false
,所以用这一行:
$unitsQuery->posts = usort($unitsQuery->posts, 'customCompare');
您正在覆盖帖子。将其更改为:
usort( $unitsQuery->posts, 'customCompare' );
我想知道为什么您必须使用 usort
而不是 WP_Query
或 posts_orderby
过滤器的 orderby
参数。