2017-09-13 77 views
0
// Start the Query 
$v_args = array(
    'post_type' => 'listing', 
    'meta_query' => array(
     array(
      'key' => 'wpcf-services', 
      'value' => $services, 
      'compare' => 'LIKE', 
     ), 
    ), 
    'tax_query' => array(
     'relation' => 'AND', 
     array(
      'taxonomy' => 'listing-city', 
      'field' => 'name', 
      'terms' => $location, 
      'compare' => 'LIKE', 
      'operator' => 'IN' 
     ), 
     array(
      'taxonomy' => 'listing-category', 
      'field' => 'name', 
      'terms' => $listing_category, 
      'compare' => 'LIKE', 
      'operator' => 'IN' 
     ), 
    ), 
); 

$listingsearch = new WP_Query($v_args); 

如果字段爲空,我想在搜索結果中顯示所有文章。如果tax_querymeta_query留空,則顯示搜索結果中的所有帖子。顯示所有文章如果字段爲空

我該如何做到這一點?

回答

2
<? if(isset($services)&&$services!=""){ 
      $meta_query[] = array(
       'key'  => 'wpcf-services', 
       'value' => $services, 
       'compare' => 'LIKE', 
       ); 
     } 


     $tax_query = array('relation'=>'AND'); 

      if(isset($location)&&$location!=""){ 
      $tax_query[] = array(
         'taxonomy' => 'listing-city', 
         'field' => 'name', 
         'terms' => $location, 
         'compare' => 'LIKE', 
         'operator' => 'IN' 
       ); 
      } 


     if(isset($listing_category)&&$listing_category!=""){ 
      $tax_query[] = array(
         'taxonomy' => 'listing-category', 
         'field' => 'name', 
         'terms' => $listing_category, 
         'compare' => 'LIKE', 
         'operator' => 'IN' 
       ); 
      }  


     $v_args = array(
      'post_type' => 'listing', 
      'meta_query' => $meta_query, 
      'tax_query' =>$tax_query, 

     ); 

$listingsearch = new WP_Query($v_args);?> 

這應該適合你。 它會檢查空的,如果找到,它會提取所有的產品。否則它會相應地獲取。讓我知道是否有更多的建議。

感謝

+0

感謝它爲我工作。 –

0

我想你可能意味着這個:

$v_args = array(
'post_type'  => 'listing', 
'meta_query' => array(
      array(
      'key'  => 'wpcf-services', 
      'value' => empty($services)?'%':$services, 
      'compare' => 'LIKE', 
      ), 
      ), 
'tax_query' =>array(
       'relation' => 'AND', 
     array(
       'taxonomy' => 'listing-city', 
       'field' => 'name', 
       'terms' => empty($location)?'%':$location, 
       'compare' => 'LIKE', 
       'operator' => 'IN' 
     ), 
     array(
       'taxonomy' => 'listing-category', 
       'field' => 'name', 
       'terms' => empty($listing_category)?'%':$listing_category, 
       'compare' => 'LIKE', 
       'operator' => 'IN' 
     ), 
     ), 

); 
相關問題