Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 显示woocommerce中当前产品的最深子类别_Php_Wordpress_Woocommerce_Categories - Fatal编程技术网

Php 显示woocommerce中当前产品的最深子类别

Php 显示woocommerce中当前产品的最深子类别,php,wordpress,woocommerce,categories,Php,Wordpress,Woocommerce,Categories,这似乎应该很容易做到,但我一直无法做到,也找不到任何关于它的帖子 我可以显示与一个产品相关的所有类别,或者顶部类别,但是如何只显示产品的最低/最深类别 Cat-A [x] Cat-B [x] Cat-C [x] Cat-D [ ] Cat-E [ ] Cat-F [ ] Cat-G [ ] Cat-H [ ] 如果这个例子是产品的祖先,我只想打印“Cat-C” 但我不想像其他解决方案那样手动设置类别级别,我希望它始终打印最低的子级,即归档页面上的产品,或

这似乎应该很容易做到,但我一直无法做到,也找不到任何关于它的帖子

我可以显示与一个产品相关的所有类别,或者顶部类别,但是如何只显示产品的最低/最深类别

Cat-A [x]
  Cat-B [x]
    Cat-C [x]
  Cat-D [ ]
Cat-E [ ]
  Cat-F [ ]
    Cat-G [ ]
      Cat-H [ ]
如果这个例子是产品的祖先,我只想打印“Cat-C”

但我不想像其他解决方案那样手动设置类别级别,我希望它始终打印最低的子级,即归档页面上的产品,或单个产品页面

你知道怎么做吗?

试试以下方法:

// get all product cats for the current post
$categories = get_the_terms( get_the_ID(), 'product_cat' ); 

// wrapper to hide any errors from top level categories or products without category
if ( $categories && ! is_wp_error( $category ) ) : 

    // loop through each cat
    foreach($categories as $category) :
      // get the children (if any) of the current cat
      $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));

      if ( count($children) == 0 ) {
          // if no children, then echo the category name.
          echo $category->name;
      }
    endforeach;

endif;

我终于在网站上找到了anwser,为woocommerce添加了适当的分类法,并在底部添加了foreach/echo来显示名称

//Get all terms associated with post in woocommerce's taxonomy 'product_cat'
$terms = get_the_terms( $post->ID, 'product_cat' );

//Get an array of their IDs
$term_ids = wp_list_pluck($terms,'term_id');

//Get array of parents - 0 is not a parent
$parents = array_filter(wp_list_pluck($terms,'parent'));

//Get array of IDs of terms which are not parents.
$term_ids_not_parents = array_diff($term_ids,  $parents);

//Get corresponding term objects.
$terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);

//Extract the name of the category from the array and post it.
foreach($terms_not_parents as $term_not_parent)
echo $term_not_parent->name;

这段代码唯一的缺点是,如果一个产品只有一个父值为0的类别,它将被破坏。我现在不需要这个功能,但我会回来用一个“如果为null,请改为执行此操作”来解决这个问题。

为什么不只检查Cat-C?查找父类别相对容易(因为
get_category()
在category类中生成一个父变量,但没有反向变量,因为一个类别可以有多个子类别。嗯,父值为0不表示顶级类别而不是底层类别吗?不是父值为0。代码说,将当前术语\u id设为父项。然后使用get\u categoryes函数返回父项(当前术语)的子项。如果没有返回帖子,这意味着它不是父项,因此它就是您要查找的子项。啊,很好!不过,我认为有一个缺点,那就是获取类别()不适用于woo,因为它将其类别存储在自定义分类法中,而不是官方wp类别位置。$categories在我尝试使用它后为空。更新了我对woocommerce产品分类法的回答(更改了2行)。您必须将其放在何处?