douchui4815 2015-02-25 23:29
浏览 41

获取具有不同参数和元数据的帖子和事件

I'm using get_posts method to get my post and events. But because of different name of arguments (event-categories and category_name) or metas (event_end and _end_ts) I used two arrays of argument and two calling of get_posts. Everything works fine but I need to order result by meta key and because of merging two arrays of posts I get sorted posts and next sorted events. Is there any option to get sorted all (better args for query or sort of array by two metas)?

This code works fine - it returns me two sorted arrays by begin date of given category in specific date range (events have time in seconds)

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);
  • 写回答

1条回答 默认 最新

  • dongyi9783 2015-02-26 19:43
    关注

    So I figured out the solution about sorting of merged array. Code looks like this:

    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;
    
    }
    

    and use of it: uasort($mergedPosts,'cmp');

    BUT does anybody know how to make it already in args?

    评论

报告相同问题?

悬赏问题

  • ¥15 lammps Gpu加速出错
  • ¥15 关于PLUS模型中kapaa值的问题
  • ¥15 关于博途V17进行仿真时无法建立连接问题
  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥15 为什么安装HCL 和virtualbox之后没有找到VirtualBoxHost-OnlyNetWork?
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号