2010-05-29 271 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; 

?>