Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Imagine i have a URL structure like this: www.domain.com/category/subcategory/

This is my code:

<?php
$args=array(
    'child_of' => $cat-id,
    'hide_empty' => 0,
    'orderby' => 'name',
    'order' => 'ASC'
);
$categories=get_categories($args);
foreach($categories as $category) { 
    echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';  } 
?>

When I'm on "www.domain.com/category/" the code correctly displays all children of the category, but when on "www.domain.com/category/subcategory/" the code doesn't display any results because the subcategory doesnt have any children. I need the code to only display the children of the top-level category even when on it's child pages.

How do i accomplish this? TIA.

share|improve this question
    
how are you defining $cat-id ? –  helgatheviking Sep 13 '12 at 20:41
    
i'm not, i dont know how to make it refer to the top level category, so it's just pulling the current category. –  CoreyRS Sep 13 '12 at 20:52
add comment

1 Answer

up vote 1 down vote accepted

Ok, try this. It should capture the current category object and then go up the chain until it finds the current categories top-most ancestor.

    // get the category object for the current category
    $thisCat = get_category( get_query_var( 'cat' ) ); 

    // if not top-level, track it up the chain to find its ancestor
    while ( intval($thisCat->parent) > 0 ) {
        $thisCat = get_category ( $thisCat->parent );
    }

    //by now $thisCat will be the top-level category, proceed as before
    $args=array(
        'child_of' => $thisCat->term_id,
        'hide_empty' => 0,
        'orderby' => 'name',
        'order' => 'ASC'
    );
    $categories=get_categories( $args );
    foreach( $categories as $category ) { 
        echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';  } 
?>
share|improve this answer
    
Worked perfectly. Thank you miss =) –  CoreyRS Sep 13 '12 at 21:31
    
You're welcome. –  helgatheviking Sep 13 '12 at 21:47
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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