如何仅显示与类别相关的所有帖子

时间:2012-09-24 作者:calebo

我正在尝试为我的分类页面制作一个自定义模板,该模板只能在特定分类下拉入帖子。目前,我只能拉在所有的职位,而不是特定类别。。。

到目前为止我的代码。。。。

<?php
    //Identify current Post-Category-ID
    foreach((get_the_category()) as $category)
    {
        $postcat= $category->cat_ID;
        $catname =$category->cat_name;
    }
?>
//Print category ID
<h2><?php echo $catname; ?></h2>
<?php 
$thumbnails = get_posts();
foreach ($thumbnails as $thumbnail) {
    if ( has_post_thumbnail($thumbnail->ID)) {
      echo \'<li><a href="\' . get_permalink( $thumbnail->ID ) . \'" title="\' . esc_attr( $thumbnail->post_title ) . \'">\';
      echo get_the_post_thumbnail($thumbnail->ID, \'full\');
      echo \'</a></li>\';
    }
}
?>

4 个回复
最合适的回答,由SO网友:Tom J Nowell 整理而成

您已经有了代码来确定要显示来自哪个类别的帖子,下面是如何获取该类别中的所有帖子:

// create a query to grab our posts in category of ID $postcat
$q = new WP_Query(array( \'cat\' => $postcat));
if($q->have_posts()){
    // foreach post found
    while($q->have_posts()){
        $q->the_post();
        // code for displaying each post goes here
    }
    // cleanup after the WP_Query, reset the post data
    wp_reset_postdata();
} else {
    // no posts were found!
}
从不使用query_posts 要进行查询,请始终检查是否确实找到了任何帖子,并始终在自己之后进行清理。

有关查询的更多参数,请参阅此处:

http://codex.wordpress.org/Class_Reference/WP_Query

SO网友:Shady M Rasmy

还有一种方法比归档更简单。php

替换该代码

<?php
get_template_part(\'loop\', $the_template_part);}
    ?> 
使用此代码

<?php
    if (is_category(\'CAT_ID\'))
        {get_template_part(\'loop2\', $the_template_part);
        } 
         else {get_template_part(\'loop\', $the_template_part);}
    ?> 
然后根据需要创建自定义循环,并将其命名为loop2或everthat,这将为您提供您想要的内容,只显示您想要创建的自定义循环中的类别帖子

SO网友:Ipstenu

我正在尝试为我的分类页面制作一个自定义模板,该模板只能在特定分类下拉入帖子。

你知道我们在WordPress中内置了分类模板。

http://codex.wordpress.org/Category_Templates

你真的可以让分类成为一个鼻涕虫。php的类别,并与它做。除非你想说你想让分类页面显示这个分类,而不是任何可能在子类或其他分类中的帖子。

SO网友:soumendu

使用以下代码可以获取该类别的所有帖子。如果要限制post的数量,则必须传递该数量以显示post参数

 <?php query_posts(\'cat=1&showposts=5\'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
    <?php the_excerpt() ?>
  </li>
<?php endwhile; endif; ?>

结束

相关推荐

Get_Posts()似乎忽略了post_type

我正在尝试获取post类型为“leads”的帖子(我使用的代码见下文),但是生成的查询(通过调试查询获得)包括“where post\\u type in(“leads”、“leads”、“product\\u description”、“custom\\u products”)”[[注意leads有两次]]这让我想到,不知何故,某种东西被挂在了这里面——但抑制\\u filters=>true不应该阻止这种情况发生吗?如果是这样的话,到底发生了什么,我如何将帖子限制为“潜在客户”? $args