在WooCommerce中获取顶级父产品类别作为身体类别 [英] Get top level parent product category as body class in WooCommerce
问题描述
我需要获取Woocommerce中产品子类别的TOP级别类别(而不仅仅是父类别).
I need to get the TOP level category (not just the parent category) of a subcategory of products in Woocommerce.
我有以下代码来获取父类别ID:
I have this code to get the parent category id:
if (is_subcategory()) {
$term = get_queried_object();
$parent_id = $term->parent;
}
这使$ parent_id作为主体类:
And this one makes $parent_id as a body class:
add_filter( 'body_class', 'parent_id_body_class' );
function parent_id_body_class( $classes ) {
// add comprehensive text followed by parent id number to the $classes array
$term = get_queried_object();
$parent_id = $term->parent;
$classes[] = 'parent-id-' . $parent_id;
// return the $classes array
return $classes;
}
这一切工作正常,但这不是顶级父类别.只是父母 我有3个级别的类别. 我对php的了解还不是很熟练.我已经搜索了很多,但是找不到如何解决这个问题的方法. 您的帮助将不胜感激.谢谢.
All this works fine, but this is NOT the top level parent category. It's just the parent. I've got 3 levels of categories. I'm not very skilled in php yet... I've searched a lot but couldn't find how figure this out. Your help would be very appreciated. Thank You.
推荐答案
下面将允许您在主体类(带注释的代码) 上显示顶级父产品类别术语ID:>
The following will allow you to display the top level parent product category term Id on the body classes (commented code):
add_filter( 'body_class', 'wc_product_cat_top_parent_id_body_class' );
function wc_product_cat_top_parent_id_body_class( $classes ) {
// Only product category archives pages
if ( is_product_category() ) {
$taxonomy = 'product_cat'; // Woocommerce product category taxonomy
// Get all parent terms Ids
$parent_terms = get_ancestors( get_queried_object_id(), $taxonomy );
// Only for product subcategories
if ( sizeof( $parent_terms ) > 0 ) {
// Loop through all parent terms Ids
foreach ( $parent_terms as $parent_id ) {
// Only the product category top level term Id
if( get_term( $parent_id, $taxonomy )->parent == 0 ) {
$classes[] = 'top-parent-id-' . $parent_id;
}
}
}
}
return $classes;
}
代码进入您的活动子主题(或活动主题)的functions.php文件中.经过测试,可以正常工作.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
这篇关于在WooCommerce中获取顶级父产品类别作为身体类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!