Skip to content

Instantly share code, notes, and snippets.

@diggeddy
Last active March 28, 2023 13:31
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/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

Some CSS to style and make toggles of labels:

.category-toggle {
  display: none;
}

.category-title {
  cursor: pointer;
  display: flex;
  align-items: center;
  position: relative;
  gap: 1em;
}

.category-title::before {
  content: "\25B8";

}

.category-toggle:checked+.category-title::before {
  transform: rotate(90deg);
}

.category-list,
.category-list li {
  list-style-type: none;
  margin-left: 0;
}

.post-list {
  display: none;
  padding: 10px 0;
}

.category-toggle:checked+.category-title+.post-list {
  display: block;
}

@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