2016-03-29 21 views
0

私はWP_Queryをユーザ入力に基づいた引数で実行するつもりです。ユーザーは複数のカテゴリ/用語を選択でき、クエリはANDブール値に基づいてフィルタリングします。何の結果は最初のクエリで返されていない場合Wordpressループ内の条件付きクエリ

// 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)と2番目のクエリを実行したいです。私は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; ?> 

これは、以前のクエリが空の場合に条件付きでクエリを呼び出す適切な方法ですか?

+0

それは機能するはずです。そうすれば、そうすれば、あなたが望むことをすることができます。それを行うには合理的な方法です。 –

答えて

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変数のタイプミス。

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