2010-05-29 269 views
1

我想知道如何防止顯示子類別帖子。我的主頁列出了來自三個「主要類別」(父類別)的所有帖子,但不幸的是它也列出了來自子類別的一些帖子。WordPress:防止顯示子類別帖子

下面是我使用得到特定類別的職位代碼:

<h2>Category Name</h2> 
<ul> 
    <?php $category_query = new WP_Query(array('category_name' => 'category1', 'showposts' => 5)); ?> 
    <?php while ($profissionais_query->have_posts()) : $profissionais_query->the_post(); ?> 
    <li> 
     <a class="title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> 
     <?php the_excerpt(); ?> 
    </li> 
    <?php endwhile; ?> 
</ul> 

有沒有人有一個想法?

謝謝。

回答

1

試試這種新的查詢方式;它只顯示一個類別。它可用於複式次頁面或後(用PHP執行啓用)不衝突:

<?php $my_query = new WP_Query('category_name=mycategory&showposts=5'); ?> 
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?> 
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"> 
<?php the_title(); ?></a> 
<?php the_excerpt(); ?> 
<?php endwhile; ?> 
+0

添加<?php wp_reset_query();?>可以在運行後銷燬自定義查詢,否則會影響頁面上運行的其他查詢。在結束之前添加它。 – Jared 2010-05-29 16:29:52

+0

songdogtech:不幸的是這段代碼沒有工作,因爲它仍然顯示子類別的帖子。你有另一個想法嗎?謝謝。 – 2010-05-29 17:12:27

+0

Carlos;我用子類進行了測試,並沒有顯示子類;子類別有自己的類別ID,必須專門調用。在沒有其他循環或代碼的頁面模板(標準WP循環除外)中嘗試使用它來隔離衝突。 Jared:它不需要wp_reset_query,因爲它是一個獨立的查詢。我在多個站點上使用它,在頁面/帖子上多次重複,並且沒有任何查詢循環發生衝突。 – markratledge 2010-05-29 17:55:06

1

這應該工作:

<?php $category_ID = $cat; // get ID of current category ?> 

<?php $excludes = get_categories('child_of='.$category_ID) ; 

    // For each child, add just the ID to an array 
    foreach ($excludes as $key => $value){ 
     $exs[] = $value->cat_ID; 
    } 

$my_query = new WP_Query(array(
      'cat' => $category_ID, 
      'category__not_in' => $exs 

)); 
if ($my_query->have_posts()) : while($my_query->have_posts()) : $my_query->the_post(); 
?> 
0

下面的代碼會顯示帖子僅從當前類別

<?php 
$current_cat = get_query_var('cat'); 

$args=array(
    'category__in' => array($current_cat), 
    'showposts' => 5 
); 

query_posts($args); 

set_query_var("cat",$current_cat); 

if (have_posts()) : 

    while (have_posts()) : the_post(); 
?> 
     <a class="title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> 
     <?php the_excerpt(); ?> 
<?php 

    endwhile; 

else : 

?> 
     <h2>Nothing found</h2> 
<?php 

endif; 

?>