今天想要获取分类文章数量,但是出现了一个问题就是文章分类我仅仅勾选了子分类,没有勾选父分类。这种情况下,通过分类相关函数获取文章数量存在一定的问题,常用的获取分类文章数量函数一般都是下面的方式:

不知道是我操作错误还是本身这个函数就不针对子分类,无法获取子分类的文章数量,该函数介绍如下:

  • get_category() 函数介绍
  • 函数用法
  • Retrieves category data given a category ID or category object.

  • 功能介绍
  • If you pass the $category parameter an object, which is assumed to be the category row object retrieved the database. It will cache the category data.

    If you pass $category an integer of the category ID, then that category will be retrieved from the database, if it isn’t already cached, and pass it back.

    If you look at get_term(), then both types will be passed through several filters and finally sanitized based on the $filter parameter value.

  • 参数介绍
  • $category
    (int|object) (Required) Category ID or category row object.
    $output
    (string) (Optional) The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Term object, an associative array, or a numeric array, respectively. Default value: OBJECT
    $filter
    (string) (Optional) How to sanitize category fields. Default value: 'raw'
  • 返回值
  • (object|array|WP_Error|null) Category data in type defined by $output parameter. WP_Error if $category is empty, null if it does not exist.
  • 所以,如果你想要获取分类及其子分类的文章数量,可能就需要曲线救国了,想要获取的方式很多,可以通过term关联获取也可以直接通过wp_query函数获取,我这边推荐使用后者:

    参考代码如上,如果你有需要的话可以直接使用看看效果。