WooCommerce定制单一产品模板

时间:2014-02-27 10:40:48

标签: php wordpress woocommerce

早上好,我正在尝试根据单个产品的类别更改标题。我正在使用Wordpress& WooCommerce 我的产品类别如下所示

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

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

基本上,当查看属于草坪商店的父类别的项目时,我需要标题为<?php get_header('lawn'); ?>,当父类别为-oak-store时,我需要标题为{{ 1}},标题之间的区别在于整个页面的样式!什么是最好的方法呢?

2 个答案:

答案 0 :(得分: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 :(得分: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' );
相关问题