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

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 );
}