2014-02-27 144 views
0

早上好,我试图根据单一产品的类别更改标题。我使用WordPress的& WooCommerce 我的产品类别是这样WooCommerce自定义单一产品模板

- the-lawn-store 
- - turf 
- - grass-seed 
- - wildflower-turf 

- the-oak-store 
- - railway-sleepers 
- - pergolas 

基本上查看该草坪店我需要的标题是<?php get_header('lawn'); ?>当父类的父类下属于一个项目时橡木商店我需要的标题是<?php get_header('oak'); ?>,标题之间的区别是整个页面的样式!什么是最好的方式去做这件事?

回答

1

那么,你需要的是父类别。为了做到这一点,首先你可以用这个获取父ID:

global $wp_query; 

$cat_obj = $wp_query->get_queried_object(); 

if($cat_obj) { 
    //print_r($cat_obj); 
    $category_ID = $cat_obj->term_id; 
    $category_parent = $cat_obj->parent; 
    $category_taxonomy = $cat_obj->taxonomy; 

    $category_parent_term = get_term_by('id', absint($category_ID), $category_taxonomy); 
    $category_parent_slug = $category_parent_term->slug; 

    get_header($category_parent_slug); 

}else{ 

    get_header(); 

    } 

取消注释的print_r来查看可用瓦尔的其余部分。测试我当地的宇和工作。

1

您不能过滤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'); 
相关问题