Skip to content

Instantly share code, notes, and snippets.

@nikola0203
Last active April 24, 2017 14:47
Show Gist options
  • Save nikola0203/60ed54a12ee5d0ab16299981df7e977c to your computer and use it in GitHub Desktop.
Save nikola0203/60ed54a12ee5d0ab16299981df7e977c to your computer and use it in GitHub Desktop.
List WordPress parent and child categories, if parent have childern display dropdown othervise clickable link.
<ul class="sidebar-menu">
<?php
$parent_terms = get_terms( 'product_cat', array( 'hide_empty' => false, 'parent' => 0 ) );
foreach( $parent_terms as $parent_term ) {
// display top level term name
$child_terms = get_terms( 'product_cat', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) );
?>
<li class="cat-item <?php if ($child_terms) { echo "have-children"; } ?>"><a href="<?php echo get_term_link($parent_term); ?>"><?php echo $parent_term->name; ?></a>
<?php if ($child_terms) : ?>
<ul class="children">
<?php foreach( $child_terms as $child_term ) : ?>
<!-- Display name of all childs of the parent term -->
<li class="cat-item"><a href="<?php echo get_term_link($child_term); ?>"><?php echo $child_term->name; ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php
}
?>
</ul>
var speed = 100;
$('.sidebar-menu > li.have-children > a').click(function(e){
e.preventDefault();
if ( ! $(this).parent().hasClass('current-cat') ){
$('.sidebar-menu li ul').slideUp(speed);
$(this).next().slideToggle(speed);
$('.sidebar-menu li').removeClass('current-cat');
$(this).parent().addClass('current-cat');
} else {
$(this).next().slideToggle(speed);
$('.sidebar-menu li').removeClass('current-cat');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment