0

I want to display all post with its own category. I tried but the loop is fetching all existing categories. Here is my code:

<?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
  • You mean sort posts by their category?
    – klewis
    Oct 17, 2016 at 14:15
  • Yes.thats what i want @blackhawk Oct 18, 2016 at 6:07

2 Answers 2

0

I don't know what you tried so far, but below you have a quick answer to list posts from a caategory by its 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();
?>
0

Use following codes.I hope it will work.

<?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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.