Skip to content

Instantly share code, notes, and snippets.

@diggeddy
Created June 5, 2023 14:06
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 diggeddy/58745c3f764cd58716a1c0e153e6626c to your computer and use it in GitHub Desktop.
Save diggeddy/58745c3f764cd58716a1c0e153e6626c to your computer and use it in GitHub Desktop.
Category post navigation with toggle-able detail
<?php
// List all categories with detail of posts in categories
function list_categories_with_posts() {
$categories = get_categories();
$output = '';
$current_post_id = get_the_ID();
foreach ($categories as $category) {
// Print toggle-able detail element for each category
$output .= '<div class="category-navigation"><details>';
$output .= '<summary>' . $category->name . '</summary>';
// set our query args
$args = array(
'category__in' => array($category->term_id),
'post_type' => 'post',
'posts_per_page' => -1,
);
$posts = new WP_Query($args);
// get posts within category
if ($posts->have_posts()) {
$output .= '<ul>';
while ($posts->have_posts()) {
$posts->the_post();
// Check if the current post matches the related post
$current_class = ($current_post_id === get_the_ID()) ? 'current-post' : '';
$output .= '<li class="' . $current_class . '"><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
$output .= '</ul>';
}
$output .= '</details></div>';
}
// Reset the post data
wp_reset_postdata();
return $output;
}
add_shortcode('category_posts', 'list_categories_with_posts');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment