TAX_QUERY(如果术语为空)

时间:2017-10-05 作者:Juan David

我很困惑,我应该通过什么才能从所有条款中获得所有帖子?现在我可以通过featured 为了得到所有events, 但如何获取所有事件?我知道我可以摆脱tax_query() 然而,我用它作为参数,在这里我可以传递一定的税,如果不是,我想要所有的帖子。

(我想要的是,如果有一个带有标记(特色)的事件,则显示该事件,如果没有带有标记(特色)的事件,则显示所有事件)

$now = date(\'d-m-Y H:i:s\');
$cat = \'featured\';
$args = array(
\'post_type\' => \'events\',
\'posts_per_page\' => 4,
\'numberposts\' => 4,
\'meta_key\' => \'start_date\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\',
\'tax_query\' => array(
  array(
      \'taxonomy\'  => \'events_tag\',
      \'field\'     => \'slug\',
      \'terms\'     => $cat,
      \'operator\'  => \'IN\'
    ),
),
\'meta_query\' => array(
  \'relation\' => \'OR\',
    array(
      \'key\' => \'start_date\',
      \'value\' => date(\'Ymd\', strtotime(\'now\')),
      \'type\' => \'numeric\',
      \'compare\' => \'>=\',
    ),
    array(
      \'key\' => \'end_date\',
      \'value\' => date(\'Ymd\', strtotime(\'now\')),
      \'type\' => \'numeric\',
      \'compare\' => \'>=\',
    ),
 ),
if (! is_null($cat))
  \'tax_query\' => array(
         array(
           \'taxonomy\'  => \'events_tag\',
           \'field\'     => \'slug\',
           \'terms\'     => $cat,
           \'operator\'  => \'IN\'
        ),
  ),
);
$wp_query = new WP_Query($args);

1 个回复
最合适的回答,由SO网友:socki03 整理而成

我会先重新组织你的$args 代码使其更有意义。

$now = date(\'d-m-Y H:i:s\');
$cat = \'featured\';
$args = $cat_args = array(
    \'post_type\' => \'events\',
    \'posts_per_page\' => 4,
    \'meta_key\' => \'start_date\',
    \'orderby\' => \'meta_value_num\',
    \'order\' => \'ASC\',
    \'meta_query\' => array(
        \'relation\' => \'OR\',
        array(
           \'key\' => \'start_date\',
           \'value\' => date(\'Ymd\', strtotime(\'now\')),
           \'type\' => \'numeric\',
           \'compare\' => \'>=\',
        ),
        array(
           \'key\' => \'end_date\',
           \'value\' => date(\'Ymd\', strtotime(\'now\')),
           \'type\' => \'numeric\',
           \'compare\' => \'>=\',
        ),
    ),
);

// Set the $cat_args array to the category tax_query
$cat_args[\'tax_query\'] = array(
                            array(
                              \'taxonomy\'  => \'events_tag\',
                              \'field\'     => \'slug\',
                              \'terms\'     => $cat,
                              \'operator\'  => \'IN\'
                            ),
                        );

if ( get_posts( $cat_args ) ) {    // See if any category posts exist
    $query_args = $cat_args;
} else {                           // Otherwise, pass original $args
    $query_args = $args;
}

// Use the newly set $query_args
$wp_query = new WP_Query($query_args);

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post