Parent category (1)
├ Child category A (1)
│ ├ Grandchild category A01 (1)
│ └ Grandchild category A02 (2)
└ Child category B (1)
. └ Grandchild category B01 (2)

The content in parentheses is the number of articles posted.
Given the structure above, I would like to see only the number of posts in the grandchild category on the archive page.

  $term_id = parent category ID;
    $term = get_term_by ('id', $term_id,'category');
    echo $term->count;

I put the above code to refer to get_term_by.
I thought that "7" including the child category would be returned, but the value returned is "0".

Ultimately, I want to get only the number of posts in the grandchild category, but is there a reason why I can't get the number of posts with get_term_by?

  • Answer # 1

    get_term_by ()I think that only items with the parent category ID will be returned.
    In the example of your question, "1" should be returned. I think you need to confirm that "0" is returned.

    $args = array (
      'parent' =>Parent category ID
    $terms = get_terms ('category', $args);

    with this$termsToChild category A,Child category BBecause the term is set,
    In the same way (loop processing as appropriate),

    $args = array (
      'parent' =>$terms->term_id // parent is child category A
    $terms = get_terms ('category', $args);

    How about the procedure of totaling as?

Related articles