Get All WordPress Category and Loop Out All Post in Each Category

Suppose you have many different posts under many different categories and in a single page you want loop out all categories serially and all posts under each category. In this WordPress query we will show you how to query to get all WordPress category and loop out all post in each category by using function get_all_category_ids.

Get All WordPress Category and Loop Out All Post in Each Category

 

Here is the sample code:

[php]

<?php
$category_ids = get_all_category_ids();
foreach($category_ids as $cat_id)
{
$cat_name = get_cat_name($cat_id);
?>
<div class="catlist">
<h1><strong><?php echo $cat_name;?></strong></h1>
<p><strong><?php echo category_description( $cat_id ); ?> </strong></p>
<?php
$args = array(
‘post_type’ => ‘post’,
‘category__in’ => $cat_id
);
$query = new WP_Query($args);
if($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
?>
<a href="<?php the_permalink();?>"><h2><?php the_title(); ?></h2></a>
<p><?php the_post(); ?></p>
<?php endwhile; endif; ?>
</div>
<?php
}
?>

[/php]

In line 2 first of all we get all the categories by get_all_category_ids function. This is an array which contains all the category ids so we get single category by running foreach loop. This loop will echo out “catlist” div for each category.  In line 7 and 8 we display category name and description. Then inside this category loop we have used WordPress query through line 11 to 16 to get all posts under each category. In line 18 and 19 we display post title and description and eventually WordPress query post ended in line 20 and foreach loop in line 23.

Like this query then check out Query to Find WordPress Category Name or id from Post id

Author: mytutorialguru

Share This Post On

Submit a Comment

Your email address will not be published. Required fields are marked *