2017-08-11 95 views
2

我創建了custom post typedishmenu。有類別在我的dishmenuSpecial,Breakfast,Lunch,Dinner。現在我想從每個類別獲得最多4條記錄(如果可用)。查詢每個類別最多4篇帖子

這是我到目前爲止已經試過:

<?php 
$menucat = get_terms('menu_category'); 
foreach($menucat as $category){ 
    $menuQuery = new WP_Query(array('post_type'=>'dishmenu','posts_per_page'=>4,'category_name'=>$category->slug)); 
    if($menuQuery->have_posts()): 
     while($menuQuery->have_posts()): $menuQuery->the_post(); 
      $price = json_decode(json_encode(get_post_meta($menuQuery->post->ID)),false); 
      echo '<div class="element-item '.$category->slug.' col-sm-6" data-category="'.$category->slug.'" > 
        <div class="dish-menu-item"> 
         <div class="dish-border-circle"> 
          <div class="dish-menu-left"></div> 
         </div> 
         <div class="dish-menu-body"> 
          <h4>'.get_the_title().'<span class="pull-right"><span class="error-text">'.$price->Price[0].'</span><sub>$</sub></span></h4> 
          <p>'.get_the_content().'</p> 
         </div> 
         <div class="dish-menu-right text-center"> 
          <p style="padding:2px; display:inline-block;"></p> 
         </div> 
        </div> 
       </div>'; 
     endwhile; 
     wp_reset_postdata(); 
    else: 
     echo '<div class="element-item '.$category->slug.' col-sm-6" data-category="'.$category->slug.'" > 
       No posts found in '.$category->slug.' 
      </div>'; 
    endif; 
} 
?> 

現在的問題是,每次else塊已被執行。

+0

您使用自定義分類的類別? –

+0

是的。 'menu_category'是分類。 –

+0

您需要在WP_Query中使用tax_query查詢。請檢查下面的答案 –

回答

1

您需要使用tax_query查詢在WP_Query

請檢查下面的查詢

$arg=array(
    'post_type'=>'dishmenu', 
    'posts_per_page'=>4, 
    'tax_query' => array(
     array('taxonomy' => 'menu_category', 
     'field' => 'slug', 
     'terms' => $category->slug, 
     'include_children' => true) 
     ) 
    ); 
$menuQuery = new WP_Query($arg); 
+0

感謝哥們!它的工作原理... :) –

+0

你是最受歡迎的。我很高興它有幫助 –

相關問題