Return to Snippet

Revision: 51928
at October 7, 2011 19:07 by innerstorm


Initial Code
/**
 * list of post's top parent category as a h3 and all subcategories of it, 
 * current post's category highlighted with a class
 */

function list_subcategories () {                                                                             
    $hide_empty = 0;                                                                                                       
    $current_class = 'current_item';                                                                                       
    global $post;

    //id of the current post
    $this_post_ID = $post->ID;                                                                                             
    
    //categories list of curent post
    $categories = get_the_category($post->ID);                                                                             
    
    //first category, parent category of current post
    $category_id = $categories[0]->cat_ID;

    // if it's not root category (0) then do
    if ($category_id) {
        
        // get alphabetical list of parent categories separated with ","
        $parentCatList = get_category_parents( $category_id, false, ",");
        
        // get first category slug of that list...
        $topParentSlug = substr( $parentCatList, 0, strpos($parentCatList, ',') );                                              
        
        // get the object of that slug
        $topParent = get_term_by( 'slug', $topParentSlug, 'category' );
        
        // get the id of that object 
        $ancestor = $topParent->term_id;
        
        // echo the name of the parent category
        echo "<h3>$topParent->name</h3>";

        //list of parent category's categories
        echo '<ul>';
        
            // making the array of subcategories objects
            $cat_array = get_categories( "echo=0&title_li=&depth=$levels&child_of=$ancestor&hide_empty=$hide_empty" );          

            foreach($cat_array as $category) { 
                
                // if the listed cat. is the current post's category, we set it as current
                if ( $category_id == $category->cat_ID ) { $is_current = "class='" .$current_class."'"; }                    
                
                // list the category with a link 
                echo '<li '. $is_current .'><a href="'.get_category_link( $category->term_id ).'">'. $category->name.'</a></li>';

            }
        echo "</ul>";
    }
}

Initial URL

                                

Initial Description

                                

Initial Title
list top parent category of post and parent\'s subcategories

Initial Tags
wordpress

Initial Language
PHP