您不能過濾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');