nielslange
1/12/2019 - 6:26 PM

List root and sub categories including their published posts

List root and sub categories including their published posts

<?php

$post_type = 'products';
$taxonomy = 'products-category';

// Fetch root categories
$root_cat_args = array(
    'taxonomy'      => $taxonomy,
    'hide_empty'    => false,
    'parent'        => 0,
    'post_status'   => 'publish',
);
$root_categories = get_categories($root_cat_args);
foreach ($root_categories as $category) {

    // Print root category titles
    printf('<h1 style="color:red;">%s</h1>', $category->slug);

    // Fetch root category posts
    $root_posts_args = array(
        'post_type' => $post_type,
        'tax_query' => array(
            array(
                'taxonomy'          => $taxonomy,
                'field'             => 'term_id',
                'include_children'  => false,
                'terms'             => $category->term_id,
            ),
        ),
    );
    $root_posts = new WP_Query($root_posts_args);
    foreach ($root_posts->posts as $post) {
        // Print root category posts
        printf('<h2 style="color:brown;">- %s</h2>', $post->post_title);
    }

    // Fetch sub categories
    $sub_cat_args = array(
        'taxonomy'      => $taxonomy,
        'hide_empty'    => false,
        'parent'        => $category->term_id,
        'post_status'   => 'publish',
    );
    $sub_categories = get_categories($sub_cat_args);
    foreach ($sub_categories as $category) {
    
        // Print sub category titles
        printf('<h1 style="color:cyan;">- %s</h1>', $category->slug);

        // Print all posts of this sub category
        $sub_posts_args = array(
            'post_type' => $post_type,
            'tax_query' => array(
                array(
                    'taxonomy'          => $taxonomy,
                    'field'             => 'term_id',
                    'include_children'  => false,
                    'terms'             => $category->term_id,
                ),
            ),
        );
        $root_posts = new WP_Query($sub_posts_args);
        foreach ($root_posts->posts as $post) {
            // Print root category posts
            printf('<h2 style="color:brown;">-- %s</h2>', $post->post_title);
        }
    }
}