Last active
January 13, 2019 10:39
-
-
Save nielslange/34378937127c476a6c5614c94415e534 to your computer and use it in GitHub Desktop.
List root and sub categories including their published posts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment