Skip to content

Instantly share code, notes, and snippets.

@diggeddy
Last active March 28, 2023 13:31
Show Gist options
  • Save diggeddy/1f5e1a23002ab4238600b00d0fb11dd0 to your computer and use it in GitHub Desktop.
Save diggeddy/1f5e1a23002ab4238600b00d0fb11dd0 to your computer and use it in GitHub Desktop.
Category Post list toggle
function category_posts_shortcode() {
// Get all categories with posts
$categories = get_categories(array(
'hide_empty' => 1
));
$output = '<ul class="category-list">';
// Loop through each category
foreach ($categories as $category) {
$output .= '<li class="category-item">';
$output .= '<input type="checkbox" id="' . $category->slug . '" class="category-toggle">';
$output .= '<label class="category-title" for="' . $category->slug . '">' . $category->name . '</label>';
$output .= '<ul class="post-list">';
// Get all posts in the category
$posts = get_posts(array(
'category' => $category->term_id,
'posts_per_page' => -1
));
// Loop through each post and add it to the output
foreach ($posts as $post) {
$output .= '<li class="post-item"><a href="' . get_permalink($post->ID) . '">' . $post->post_title . '</a></li>';
}
$output .= '</ul>'; // .post-list
$output .= '</li>'; // .category-item
}
$output .= '</ul>'; // .category-list
return $output;
}
add_shortcode('category_posts', 'category_posts_shortcode');
@diggeddy
Copy link
Author

To use - add: [category_posts] shortcode to where you want it displayed.

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