尝试显示某个类别中的所有帖子

时间:2016-10-17 作者:Govind Jangid

我想用自己的类别显示所有帖子。我尝试了,但循环正在获取所有现有类别。这是我的代码:

<?php //query to echo the categories 
 $cat_counts = wp_list_pluck( get_categories(),\'count\', \'name\' );?>
   <?php foreach ( $cat_counts as $name => $count ) {?>
     <li>
       <a href="#"><?php echo $name;?></a>
       <a href=\'#\' class=\'pull-right\'><?php echo sprintf( "%02d", $count ) ;?></a><br/>
     </li>

2 个回复
SO网友:Cristian Stan

我不知道到目前为止你尝试了什么,但下面你有一个快速的答案,可以根据ID列出一个类别中的帖子。

<?php 
$args = array(
    \'posts_per_page\'   => -1, // Will show all posts from the category
    \'cat\'              => 149, // ID of the category
    \'orderby\'          => \'post_date\',
    \'order\'            => \'DESC\',
    \'post_type\'        => \'post\',
    \'post_status\'      => array(\'publish\')
); 

$posts_list = get_posts( $args );
foreach ( $posts_list as $post ) :
  setup_postdata( $post ); ?> 
    <article>
        <li>
        <?php echo get_the_date(); ?>
        <?php echo get_the_title(); ?>   
        <?php echo get_the_excerpt(); ?>
        Category: <?php echo get_the_term_list( $post->ID, \'category\', \'\', \' \' ); ?>
        </li>
    </article>
<?php
endforeach; 
wp_reset_postdata();
?>

SO网友:bdtheme

使用以下代码。我希望它能起作用。

<?php 

$terms = wp_get_post_terms( $post->ID, array(\'Your category name\') );
$term_slugs = wp_list_pluck( $terms, \'slug\' );     
$args = array(
        \'post_type\' => array( \'your post  name\' ), //
            \'tax_query\' => array(
                array(
                \'taxonomy\' => \'category name\',
                \'field\' => \'slug\',
                \'terms\' => $term_slugs
                )
    );


    $my_query = null;
    $my_query = new WP_Query($args);

相关推荐

按ASC或DESC对wp_Dropdown_Categories进行排序

我有一个在标题中搜索的网站(anunciaya.es)。我想按名称ASC/DESC订购wp\\U下拉列表\\U类别,但它不适合我。\'排序依据\'=>;\'“名称”和“顺序”=>;\'DESC不适合我。有什么解决方案吗?以下是PHP代码:wp_dropdown_categories( array( \'show_option_none\' => $cat_text, \'option_none_value\' => \'\', \'ta