Skip to content

Instantly share code, notes, and snippets.

@FreshLondon
Forked from nielslange/functions.php
Last active January 13, 2019 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FreshLondon/4f453217aca5c53ba2605640b41dc2c5 to your computer and use it in GitHub Desktop.
Save FreshLondon/4f453217aca5c53ba2605640b41dc2c5 to your computer and use it in GitHub Desktop.
List root and sub categories including their published posts
<div class="menu-main-menu-container">
<ul id="primary-menu" class="menu nav-menu" aria-expanded="false">
<?php
$root_cat_args = array('taxonomy' => 'products-category', 'hide_empty' => false, 'parent' => 0);
$root_categories = get_categories($root_cat_args);
foreach ($root_categories as $category) {
// Print all root category title
printf('<li><span>%s</span><ul class="depth-one">', $category->slug);
//debug($category);
// Print all posts of this root category
$root_posts_args = array(
'post_type' => 'products',
'tax_query' => array(
array(
'taxonomy' => 'products-category',
'field' => 'term_id',
'include_children' => false,
'terms' => $category->term_id,
),
),
);
$root_posts = new WP_Query($root_posts_args);
//debug($root_posts);
foreach ($root_posts->posts as $post) {
#debug($post);
$postPermalink = get_the_permalink();
$postTitle = get_the_title();
printf('<li><a href="' . $postPermalink . '">' . $postTitle . '</a></li>');
}
//debug($category);
$sub_cat_args = array('taxonomy' => 'products-category', 'hide_empty' => false, 'parent' => $category->term_id);
$sub_categories = get_categories($sub_cat_args);
foreach ($sub_categories as $category) {
// Print all sub category title
printf('<li><span>%s</span><ul class="depth-two">', $category->slug);
// Print all posts of this sub category
$sub_posts_args = array(
'post_type' => 'products',
'tax_query' => array(
array(
'taxonomy' => 'products-category',
'field' => 'term_id',
'include_children' => false,
'terms' => $category->term_id,
),
),
);
$root_posts = new WP_Query($sub_posts_args);
//debug($root_posts);
foreach ($root_posts->posts as $post) {
#debug($post);
$postPermalink = get_the_permalink();
$postTitle = get_the_title();
printf('<li><a href="' . $postPermalink . '">' . $postTitle . '</a></li>');
}
//print('posts');
echo '</ul></li>';
}
echo '</ul></li>';
}
function debug($data) {
print('<pre>');
print_r($data);
print('</pre>');
}
?>
</ul>
</div>
@FreshLondon
Copy link
Author

Added the list tags to make this into an UL with nested UL/LI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment