I recently created a theme and then wanted to add a routine to show my Post categories in a vertical hierarchical menu.
This routine lists the top level category with a count of child posts.
On clicking a category name, the child posts are revealed.
I tried to use a plugin ‘collapse categories’ which should have worked, but the plugin doesn’t work with Bootstrap.css or jquery.1.10+
The routine uses a combination of PHP, Javascript & jQuery.
Work with the routine on the sidebar of the Post of this blog.
The css styles are listed at the bottom of the page
<?php
// set the arguments for the query
$args = array(
‘post_type’ => ‘post’,
‘orderby’ => ‘name’,
‘order’ => ‘ASC’,
‘hide_empty’ => 1,
‘depth’ => 1,
‘posts_per_page’ => -1
);
$categories = get_categories( $args );
// echo each category and create ul (list) for their child posts
echo “<div class=’pcl_category’>”;
foreach ( $categories as $category ) {
echo “<h2 onclick=\”unhide(‘”.$category->slug.”‘);\”>”; //
echo $category->name .” (“.$category->category_count.”)”;
echo “</h2>”;
$args[‘category’] = $category->term_id;
$posts = get_posts($args); ?>
<div class=”post_cat_list”>
<ul id=”<?php echo “pcl_”.$category->slug;?>”>
<?php foreach($posts as $post) { ?>
<li><a href=”<?php the_permalink()?>”><?php the_title(); ?></a></li>
<?php } ?>
</ul>
</div>
<?php }
echo “</div>”;
// reset query after you’re finished with it
wp_reset_query();
?>
// use standard javascript to work with cookies.
// cookies will determine which category list is open
<script>
writeCookie = function(cname, cvalue, days) {
var dt, expires;
dt = new Date();
dt.setTime(dt.getTime()+(days*24*60*60*1000));
expires = “; expires=”+dt.toGMTString();
document.cookie = cname+”=”+cvalue+expires+’; domain=bluelily.com.au’;
}
function readCookie(name) {
var nameEQ = name + “=”;
var ca = document.cookie.split(‘;’);
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==’ ‘) c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
// use jquery to hide/reveal category lists using jQuery routines
$(function() {
$(‘[id^=”pcl_”]’).hide();
$menuID = readCookie(‘pcl_category’);
$(“#pcl_”+$menuID).show();
});
function unhide($menuID){
$(‘[id^=”pcl_”]’).hide();
$(“#pcl_”+$menuID).delay(50).fadeIn(500);
writeCookie(‘pcl_category’,$menuID,30);
};
</script>
<style>
.pcl_category{text-align: left}
.pcl_category h2{font-size:18px; font-weight: 500; margin-left:20px}
.pcl_category h2:hover{cursor:pointer; text-decoration: underline}
.post_cat_list ul{text-align: left; margin-left:-5px}
.post_cat_list li{line-height: 22px; list-style-type: none}
</style>