Chandra Patel

Just Another Developer

Display category and post list in WordPress

Hello friends, Today we learn how to display all category list and each category list contain own post list. This example also work for all custom taxonomies and custom post types.

Here is simple example,

  • Category 1
    • Post 1
    • Post 2
  • Category 2
    • Post 3
    • Post 4

Below is simple code for display category – post tree. Code is very simple. You can easily understood.

<?php
$taxonomy = 'category'; // Here, you can pass custom taxonomy also.

$args = array(
     'orderby' => 'name',
     'order' => 'ASC',
     'taxonomy' => $taxonomy 
);

// Get All categories.
$categories = get_categories($args); 
        
echo "<ul class='category-list'>";
        
foreach($categories as $category) {
        
   echo '<li>
            <a href="' . get_term_link( $category, $taxonomy ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>
         </li> ';
            
         $post_args = array(
                'tax_query' => array(
                    array(
                        'taxonomy' => $taxonomy,
                        'field' => 'term_id',
                        'terms' => $category->term_id
                    )
                ),
                'posts_per_page'=> -1 // list all post.
         );
         
         $wp_query = new WP_Query($post_args); // Fetch all post related to taxonomy.
            
            if ($wp_query->have_posts()) :
                
                echo "<ul class='post-list'>";
                
                while ($wp_query->have_posts()) : $wp_query->the_post();
                
?>
                    <li>
                        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" ><?php the_title(); ?></a>
                    </li>
<?php
                endwhile;   
                echo "</ul>";    
            endif;
        }
        echo "</ul>";
    }
?>