How to get all posts of a specific category or sub category in wordpress?Here I’m going to explain how to get all posts of a specific category or sub category.
You can execute wordpress query to get specific category details as follows.
1 2 3 4 5 6 7 8 9 |
$category_id = 10;// my category ID $args = array( 'cat' => $category_id, 'post_type' => 'post', 'posts_per_page' => 9, // number of posts to a page 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), // pagination ); $cat_query = new WP_Query($args); |
This will return all posts of that category query.Now we can get all posts using while loop.
1 2 3 4 5 6 7 8 |
if( $cat_query->have_posts() ) : $count=0; while ( $cat_query->have_posts() ) : $cat_query->the_post(); // ---------------------- display post details here -------- endwhile; endif; // reset query wp_reset_query(); |
Her is the full code to get all details with thumbnails of each posts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php $args = array( 'cat' => $category_id, 'post_type' => 'post', 'posts_per_page' => 9, 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), ); $cat_query = new WP_Query($args); if( $cat_query->have_posts() ) : $count=0;?> <section id="related_posts"> <div class="post-listing"> <?php while ( $cat_query->have_posts() ) : $cat_query->the_post()?> <div class="related-item"> <?php if ( function_exists("has_post_thumbnail") && has_post_thumbnail() ) : ?> <div class="post-thumbnail"> <a href="<?php the_permalink(); ?>" title="<?php printf( __( 'Permalink to %s', 'tie' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"> <?php tie_thumb('', 300 ,160); ?> <?php tie_get_score( ); ?> </a> </div><!-- post-thumbnail /--> <?php endif; ?> <h3><a href="<?php the_permalink(); ?>" title="<?php printf( __( 'Permalink to %s', 'tie' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php $tit = the_title('','',FALSE); echo substr($tit, 0, 50);if (strlen($tit) > 50) echo " ...";?></a></h3> <p class="post-meta"><?php tie_get_time() ?></p> </div> <?php endwhile;?> <div class="clear"></div> </div> </section> <?php endif; wp_reset_query(); ?> |