在 WooCommerce 中获取顶级 parent 产品类别作为正文 class
Get top level parent product category as body class in WooCommerce
我需要获取 Woocommerce 中产品子类别的顶级类别(而不仅仅是 parent 类别)。
我有这段代码可以获取 parent 类别 ID:
if (is_subcategory()) {
$term = get_queried_object();
$parent_id = $term->parent;
}
这一个使 $parent_id 成为一个主体 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;
}
这一切都很好,但这不是顶级 parent 类别。只是 parent。
我有 3 个级别的类别。
我在 php 方面还不是很熟练......我搜索了很多但找不到解决办法。
非常感谢您的帮助。谢谢。
以下将允许您在正文中显示顶级父产品类别术语 ID 类 (注释代码):
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 文件。已测试并有效。
我需要获取 Woocommerce 中产品子类别的顶级类别(而不仅仅是 parent 类别)。
我有这段代码可以获取 parent 类别 ID:
if (is_subcategory()) {
$term = get_queried_object();
$parent_id = $term->parent;
}
这一个使 $parent_id 成为一个主体 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;
}
这一切都很好,但这不是顶级 parent 类别。只是 parent。 我有 3 个级别的类别。 我在 php 方面还不是很熟练......我搜索了很多但找不到解决办法。 非常感谢您的帮助。谢谢。
以下将允许您在正文中显示顶级父产品类别术语 ID 类 (注释代码):
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 文件。已测试并有效。