Wordpress循环中的条件查询

时间:2016-03-29 21:37:07

标签: php wordpress

我将使用基于用户输入的参数运行WP_Query。用户可以选择多个类别/术语,查询将根据AND布尔值进行过滤。

// main arguments
$args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'industry',
            'terms'    => $user_input,
        ),
        array(
            'taxonomy' => 'format',
            'terms'    => $user_input2,
        ),
    ),
);

// less specific arguments
$lessargs = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'industry',
            'terms'    => $user_input,
        ),
    ),
);

如果第一个查询中没有返回任何结果,我想以较低的特​​异性运行第二个查询($ lessargs)。我知道我需要使用if / else语句,但我不知道在循环中执行此操作的正确方法。例如:

<?php $the_query = new WP_Query( $args ); ?>

<?php if ($the_query->have_posts()) : ?>

     <?php while ($the_query->have_posts()) : the_post(); ?>
        // Return Query Results
     <?php endwhile; ?>

  <?php else : ?>

    <?php $the_second_query = new WP_Query( $less_args ); ?>

    <?php while ($the_second_query->have_posts()) : the_post(); ?>
        // Return Second Query Results
    <?php endwhile; ?>

<?php endif; ?>

如果前一个查询返回空,这是否有条件地调用查询?

2 个答案:

答案 0 :(得分:0)

每当我需要自定义查询时,我总是会构建自己的循环。

你可以这样做,

# First Argument
$args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'industry',
            'terms'    => $user_input,
        ),
        array(
            'taxonomy' => 'format',
            'terms'    => $user_input2,
        ),
    ),
);
# Second Argument
$lessargs = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'industry',
            'terms'    => $user_input,
        ),
    ),
);

$query = new WP_QUery( $args ); //Run First Query

$posts = $query->get_posts(); //Get Post of first Query

if ( !$posts ) { //If no post on First query Run Second Query
    $query = new WP_QUery( $lessargs );
    $posts = $query->get_posts(); //Get Post of second query
}
if ( !$posts ) return 'No Result Found'; //stop execution if no results
foreach( $posts as $post ) { //Loop through each result
        _e( $post->post_title ); // Echo the title
    }
} 

答案 1 :(得分:0)

我会稍微改变一下,只是为了迎合这两个查询都不会返回任何行的事实:

$the_query = new wp_query($args);
if ($the_query->have_posts()) {
    while ($the_query->have_posts()) {
        the_post();
        // Return Query Results
    }
} else {
    $the_query = new wp_query($lessargs);
    if ($the_query->have_posts()) {
        while ($the_query->have_posts()) {
            the_post();
            // Return Second Query Results
        }
    } else {
        echo '<p>No posts found.</p>';
    }
}

请注意,您的$lessargs变量存在拼写错误。

相关问题