Wp_Query参数中的IF语句

时间:2020-03-19 作者:user3492770

我使用$\\u POST表单从表单中获取多个元素。主要问题是当我有多个“if语句”时。当我想检查是否存在多个字符串时,嵌套语句可能会变得一团糟。。。

$cat = // Categories

if(!empty($cat)) {
   $args = array(  
    \'post_type\' => \'domains\',
    \'post_status\' => \'publish\',
      \'tax_query\' => array(
          array (
              \'taxonomy\' => \'domain_categories\', 
              \'field\' => \'slug\',
              \'terms\' => $cat, // ELEMENT EXISTS FOR $cat
          ),
      ), 
); 
} else { // ELSE STATEMENT IF $cat DOESN\'T EXIST
    $args = array(  
        \'post_type\' => \'domains\',
        \'post_status\' => \'publish\',
    );
} // END STATEMENT FOR $cat
所以,我希望能够简化这一点。

1 个回复
SO网友:user3492770

正如这里所说:Conditional arguments for WP_Query and tax_query depending on if $somevar has a value

我可以在WP\\u查询实例化之外定义参数:

<?php
$tax_query = array(\'relation\' => \'AND\');
    if (isset($search_course_area))
    {
        $tax_query[] =  array(
                \'taxonomy\' => \'course-area\',
                \'field\' => \'id\',
                \'terms\' => $search_course_area
            );
    }
    if (isset($search_course_level))
    {
        $tax_query[] =  array(
                \'taxonomy\' => \'study-levels\',
                \'field\' => \'id\',
                \'terms\' => $search_course_level
            );
    }
    if (isset($search_course_mode))
    {
        $tax_query[] =  array(
                \'taxonomy\' => \'course-mode\',
                \'field\' => \'id\',
                \'terms\' => $search_course_mode
            );
    }

$query = new WP_Query(
    array(
        //Retreive ALL course posts
        \'post_type\' => \'course\',
        \'posts_per_page\' => \'-1\',
        //Filter taxonomies by id\'s passed from course finder widget
        \'tax_query\' => $tax_query,
    )
);
?>

相关推荐

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

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