简体   繁体   English

WordPress将类别父母作为类别数组

[英]Wordpress get category parents as category array

If you look at the documentation for get_category_parents() you'll see that it resturns a string where the names of the categories are seperated by a seperator. 如果查看get_category_parents()的文档,您会发现它返回一个字符串,其中类别名称由分隔符分隔。 Now, I don't know if this is just me but this seems extremely stupid. 现在,我不知道这是否只是我自己,但这看起来非常愚蠢。 What I'm expecting is an array of actual category objects. 我期望的是一组实际的类别对象。 Can't have everything I guess.. 我猜不到所有内容。

What would be the best way to get the parent categories in the format that I want them? 以我想要的格式获取父类别的最佳方法是什么?

Try something like this: 尝试这样的事情:

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

Not tested. 未经测试。

Try this one you will get correct result 试试这个你会得到正确的结果

if your want to get parent category of a post then try this 如果您想获取帖子的父类别,请尝试此

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

if you want get parent with category id then try this one... 如果您想让父母获得类别ID,请尝试使用此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;
   }

function to place in functions.php 函数放置在functions.php中

call this function in your page, post or custom template 在页面,帖子或自定义模板中调用此函数

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

Here is the function that return you most parent category or custom taxonomy Tested!!! 这是返回大多数父类别或自定义分类标准的函数!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM