Wordpress 获取类别父级作为类别数组

Wordpress get category parents as category array

如果您查看 get_category_parents() 的文档 您会看到它返回一个字符串,其中类别名称由分隔符分隔。现在,我不知道这是否只是我,但这看起来非常愚蠢。我期待的是一组实际的类别对象。不能拥有我猜的一切..

以我想要的格式获取父类别的最佳方法是什么?

尝试这样的事情:

$categories = [];
$parents = get_category_parents( $cat, false, ',' );
foreach($parents as $parent){
    $categories[] = get_term_by('name', $parent, 'category');
}

未测试。

试试这个你会得到正确的结果

如果你想获得 post 的父类别,那么试试这个

    $parent_cat_array = get_post_ancestors( $post ); //$post is an object or you can pass post id also

如果你想获得具有类别 ID 的父对象,请尝试这个...

    // determine the topmost parent of a term
   function get_term_top_most_parent($term_id, $taxonomy) {
      // start from the current term
      $parent = get_term_by('id', $term_id, $taxonomy);
      // climb up the hierarchy until we reach a term with parent = '0'
      while ($parent->parent != '0') {
         $term_id = $parent->parent;

         $parent = get_term_by('id', $term_id, $taxonomy);
      }
      return $parent;
   }

要放置在 functions.php

中的函数

在您的页面中调用此函数,post或自定义模板

      $term_parent = get_term_top_most_parent($term_id, $taxonomy);
      // in case of default category then your taxonomy is category

这是return您最父类别或自定义分类法的功能 已测试!!!