我正在使用get_posts方法来获取我的帖子和事件。但是,由于参数的名称(事件类别和类别名称)或元(事件_end和_end_ts)不同,我使用了两个参数数组和两个get_posts调用。一切都很好,但我需要按元键对结果进行排序,由于合并了两个帖子数组,我得到了排序的帖子和下一个排序的事件。有没有任何选项可以全部排序(更好的查询参数或按两个元对数组排序)?
这段代码工作得很好——它按特定日期范围内给定类别的开始日期向我返回两个排序的数组(事件的时间以秒为单位)
if($toDate != date('Y/m/d',strtotime(0)))
{
$secondCondition = array(
'key' => 'event_begin',
'value' => $toDate,
'compare' => '<=',
'type' => 'date'
);
$secondCondition2 = array(
'key' => '_start_ts',
'value' => strtotime($toDate),
'compare' => '<=',
'type' => 'numeric'
);
}
else
{
$secondCondition = "";
}
$query1 = array(
'category_name' => $category,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => 'event_begin',
'meta_query' => array(
array(
'key' => 'event_end',
'value' => $fromDate,
'compare' => '>=',
'type' => 'date'
),
$secondCondition
)
);
$query2 = array(
'post_type' => 'event',
'event-categories' => $category,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => '_start_ts',
'meta_query' => array(
array(
'key' => '_end_ts',
'value' => strtotime($fromDate),
'compare' => '>=',
'type' => 'numeric'
),
$secondCondition2
)
);
$postGroup1 = get_posts( $query1);
$postGroup2= get_posts( $query2);
$mergedPosts = array_merge($postGroup1, $postGroup2);
所以我找到了合并数组排序的解决方案。代码如下:
function cmp($a,$b)
{
if ($a->post_type == "event")
$fromCmpA = get_post_meta($a->ID,"_start_ts",true);
else
$fromCmpA = strtotime(get_post_meta($a->ID,"event_begin",true));
if ($b->post_type == "event")
$fromCmpB = get_post_meta($b->ID,"_start_ts",true);
else
$fromCmpB = strtotime(get_post_meta($b->ID,"event_begin",true));
if ($fromCmpA == $fromCmpB)
return 0;
return ($fromCmpA < $fromCmpB) ? -1 : 1;
}
及其用途:uasort($mergedPosts,'cmp');
但是有人知道如何在args中制作它吗?