WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Display Categories Assigned to a Post (with hierarchical list styling) (3 posts)

  1. Pete
    Member
    Posted 5 months ago #

    I have some code that shows how to "Display Categories Assigned to a Post" with each category separated by a
    . However, I'd like to display this in a list/hierarchical tree.

    Any help greatly appreciated.

    Love Pete x

    This is what I have...

    <?php
    $taxonomy = 'category';
    
    // get the term IDs assigned to post.
    $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
    // separator between links
    $separator = ', ';
    
    if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
    
    	$term_ids = implode( ',' , $post_terms );
    	$terms = wp_list_categories( 'title_li=&style=list&hierarchical=1&echo=1&taxonomy=' . $taxonomy . '&include=' . $term_ids );
    	$terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );
    
    	// display post categories
    	echo  $terms;
    }
    ?>

    But i'd

  2. bcworkz
    Member
    Posted 5 months ago #

    Your post got clipped, but I think I understand what you want. You need to edit down the if(){} block to this:

    if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
    	$term_ids = implode( ',' , $post_terms );
    	wp_list_categories( 'title_li=&style=list&hierarchical=1&echo=1&taxonomy=' . $taxonomy . '&include=' . $term_ids );
    }

    everything above the if line remains the same.

  3. Pete
    Member
    Posted 5 months ago #

    Perfect! Works like a charm... Thanks heaps.

Reply

You must log in to post.

About this Topic