0

I found a great piece of code for my category.php file to list categories for a specific taxonomy (not tested). BUT - how can I change the code (or achieve it) to show the default Wordpress categories like:

If the current category is a top level category (myewebsite.com/category/toplevel), list ONLY the children categories:

Child 1
Child 2
Child 3

But if the current category is not a top level category (myewebsite.com/category/toplevel/parent), it should show ONLY its sibling categories:

Sibling 1
Sibling 2
Sibling 3

Here is the code i found:

    <?php
$term = get_queried_object()->term_id;
$termid = get_term($term, 'product_cat' );
if($termid->parent > 0)
{
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'child_of' => $termid->parent,
);
$siblingproducts = get_terms( 'product_cat', $args);
foreach ($siblingproducts as $siblingproduct) {
if ($siblingproduct->term_id == $term ) { ?>
<li>
<?php } else { ?>
<li>
<?php } ?>
<a href="<?php echo get_term_link( $siblingproduct ); ?>"><?php echo $siblingproduct->name; ?><?php echo "<span class='count'>" . $siblingproduct->count . "</span>"; ?></a></li>
<?php }
} else {
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'child_of' => $term
);
$subproducts = get_terms( 'product_cat', $args);
foreach ($subproducts as $subproduct) { ?>
<li> <a href="<?php echo get_term_link( $subproduct ); ?>"><?php echo $subproduct->name; ?><?php echo "<span class='count'>" . $subproduct->count . "</span>"; ?></a></li>
<?php }
}
?>

Any suggestions on how to change the code would be greatly appreciated!

  • Simply change all instances of product_cat with category – Pieter Goosen Oct 22 '14 at 8:53
  • Your suggestion do not work...? – NewUser Oct 22 '14 at 9:16
  • What do you mean by do not work. – Pieter Goosen Oct 22 '14 at 9:29
  • It lists all the categories one by one - regardles wich cat im on... – NewUser Oct 22 '14 at 9:32
  • I cannot do any tests now. Do a var_dump($variable_to_test); and dump the result of every variable after the variable and check if the values returned are correct – Pieter Goosen Oct 22 '14 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.