Display a list of subcategories (from specific Category) a post belongs to

This code almost works, but it brings other categories that I do not want to display (minimun of 1, maximun of 3). I have several categories and subcategories, that can be marked at the same post, but I just want to display subcategories that are marked and that are child of cat id=59 (example).

Code:

$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 = ', ';
$categories = get_the_category();
$parentid = $categories[0]->category_parent;
$parents = get_terms( 'category', array( 'parent' => 59 ) );
if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {

    $term_ids = implode( ',' , $post_terms );
    $terms = wp_list_categories( 'title_li=&style=none&echo=0&child_of=' . $parentid . '&taxonomy=' . $taxonomy . '&include=' . $term_ids );
    $terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );

    // display post categories
    echo  $terms;
}

enter image description here

enter image description here

Answers 1

  • So your problem is that you've essentially mixed up what looks like 3 separate attempts at a solution. There's a lot of redundant code in there that's making it confusing to read. The actual line of code that's generating the output that you're seeing is this one:

    $terms = wp_list_categories( 'title_li=&style=none&echo=0&child_of=' . $parentid . '&taxonomy=' . $taxonomy . '&include=' . $term_ids );
    

    The problem is that here you've set child_of=' . $parentid, but $parentid isn't set to 59, it's set to this:

    $parentid = $categories[0]->category_parent;
    

    There's no guarantee this will be the specific category that you want. The order of categories returned by get_the_category() is the order that the categories were added to the post. This isn't necessarily a category with 59 as its parent. If the first category doesn't have a parent, then this function will list all categories.

    If you want:

    • List categories for the current post.
    • The categories should be children of category 59.
    • No more than 3 should be displayed.
    • The categories should be separated by commas.

    Then this is all the code you need:

    $categories = wp_get_object_terms( $post->ID, 'category', [ 'parent' => 59, 'number' => 3 ] );
    
    if ( ! empty( $categories ) ) {
        $category_links = [];
    
        foreach ( $categories as $category ) {
            $category_links[] = '<a href="' . esc_url( get_term_link( $category ) ) . '">' . $category->name . '</a>';
        }
    
        echo implode( ', ', $category_links );
    }
    

Related Questions