0

I've made a basic subcategory nav menu using the code below.

The problem is on one category (with NO children), it returns the Top Level categories as children, e.g.: News, Uncategorized, etc. (I've tried assigning a child category and it actually disappears from the menu instead of fixing things)

What could be causing this?

function display_category_breadcrumbs () {
    $current_cat_id = get_cat_id( single_cat_title("",false) );    
    $parent_cats = get_categories('parent='.$current_cat_id);  

    ?> <ul id="cat-breadcrumb"> <?php
    foreach ($parent_cats as $sub_category ) {
        echo '<li><a href="'. esc_url( get_category_link( $sub_category->term_id) ) . '">' . esc_html( $sub_category->cat_name) . '</a></li>';
    }
    ?> </ul> <?php
}

1 Answer 1

0

I believe what you're seeing is the expected behavior when parent is set to 0 which is what get_cat_id() returns if it fails to find a category ID for the $cat_name argument. You can quickly test this by putting var_dump($current_cat_id); anytime after you set it to see if this guess is right. If so, you'll need to figure out why you're not getting a $current_cat_id.

The way you're doing it right now strikes me as fairly error-prone though it's hard to know without more context. I'd look to get the ID directly from a get_the_terms() if you're on single posts or maybe with get_query_var() if on a term archive page.

Tangentially, your code shouldn't be working at all if what you pasted is unedited since your if statement has no test to perform.

2
  • Thanks, mrwweb. Could you tell me more about what you mean by error-prone? The error only shows up in production (so var_dump is a last resort ), and on staging the exact same category doesn't display the same error. Deleted the "if", thanks for the heads up ( copied a version I had started editing: the if is not the issue. ) :)
    – Seb
    Commented Jun 2, 2015 at 14:31
  • If there's a way to directly get the ID rather than transform the term, that's going to work more often, I suspect. Re: production, you can always var_dump into an html comment: <!-- <?php var_dump( $current_cat_id ); ?> -->
    – mrwweb
    Commented Jun 2, 2015 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.