• Resolved jrcollins

    (@jrcollins)


    I’m trying customize my category template to display a list of the current categories child categories.
    However, I want to reference some custom variables in the output so can’t use wp_list_categories. The list will include the tile and link of child category, a thumbnail and the category description.

    This is what I’ve got so far:

    <?php if ( is_category() ); {
    $cat_id = get_category(get_query_var( 'cat' ));
    $termchildren = get_term_children( $cat_id, $category );

    Can anyone advise me on the best way to do this?
    Should I use get_term_by to return the data for each child category?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Perhaps something like this?

    $cat_id = get_category( get_query_var( 'cat' ) );
    
    $categories = get_categories(
        array( 'parent' => $cat_id )
    );

    This should give you an array of all child categories of the parent. Then, all you need to do is loop them, and extract what info you need.

    foreach( $categories as $cat ) {
    
        echo '<li>'.$cat->name.'</li>';
    }

    That should give you a list of all child categories names. You can use ‘var_dump( $cat )’ inside the loop to see what other values you can retrieve. I know you can also use `$cat->description’ to get the category description.

    Thread Starter jrcollins

    (@jrcollins)

    Thanks, I tried that but I got an error for some reason.

    Thread Starter jrcollins

    (@jrcollins)

    I tried the following but it’s not returning anything:

    <?php 
    
    $catid = get_category(get_query_var( 'cat' ));
    
    $termchildren = get_term_children( $catid, 'category' );
    
    echo '<ul>';
    
    foreach( $termchildren as $cat ) {
    
    $term = get_term_by( 'id', '$cat', 'category' );
    
    echo '<li>'.$term->name.'</li>';
    
    }
    
    ?>
    Thread Starter jrcollins

    (@jrcollins)

    I got it working now. I just modified your code slightly. Thanks for your help.

    Here’s the working code:

    <?php 
    
    $cat = get_category( get_query_var( 'cat' ) );
    $cat_id = $cat->cat_ID;
    $child_categories=get_categories(
        array( 'parent' => $cat_id )
    );
    
    foreach ( $child_categories as $child ) {
        // Here I'm showing as a list...
        echo '<li>'.$child ->cat_name.'</li>';
    }
    
    ?>

    Great!! 🙂

    Sorry, I had to leave yesterday. Super glad you got it working properly! Nice.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Custom category template’ is closed to new replies.