您不能过滤get_header()
函数,因此您必须重写WooCommerce的single-product.php
模板。从那里,你可以修改该文件的开头:
get_header('shop'); ?>
我创建了下面的函数来获得任何产品的顶级产品类别:
function kia_get_the_top_level_product_category($post_id = null){
$product_cat_parent = null;
if(! $post_id){
global $post;
$post_id = $post->ID;
}
// get the product's categories
$product_categories = get_the_terms($product_id, 'product_cat');
if(is_array($product_categories)) {
// gets complicated if multiple categories, so limit to one
// on the backend you can restrict to a single category with my Radio Buttons for Taxonomies plugin
$product_cat = array_shift($product_categories);
$product_cat_id = $product_cat->term_id;
while ($product_cat_id) {
$cat = get_term($product_cat_id, 'product_cat'); // get the object for the product_cat_id
$product_cat_id = $cat->parent; // assign parent ID (if exists) to $product_cat_id
// the while loop will continue whilst there is a $product_cat_id
// when there is no longer a parent $product_cat_id will be NULL so we can assign our $product_cat_parent
$product_cat_parent = $cat->slug;
}
}
return $product_cat_parent;
}
然后在你的主题single-product.php
你可以做:
$parent = kia_get_the_top_level_product_category();
if($parent == 'oak'){
get_header('oak');
} elseif($parent == 'lawn'){
get_header('lawn');
} else {
get_header('shop');
}
如果您还没有一个具体header-shop.php
做,那么你可以在技术上也做:
$parent = kia_get_the_top_level_product_category();
get_header($parent);
当WooCommerce升级时,覆盖此模板可能会使您处于风险之中。作为替代,我会建议过滤身体类。
function wpa_22066003_body_class($c){
if(function_exists('is_product') && is_product() && $parent = kia_get_the_top_level_product_category()){
$c[] = $parent . '-product-category';
}
return $c;
}
add_filter('body_class', 'wpa_22066003_body_class');