WooCommerce - determine product category of current single product page

时间:2017-04-06 16:44:03

标签: php wordpress woocommerce categories product

In my header.php I want to add title based on the category of the page.

My current code looks like this:

<h1 class="page-title"><?php

    if (is_category('english') || has_category('english',$post->ID)) {

        echo "music in the world of noise";

    } elseif (is_category('marathi') || has_category('marathi',$post->ID)) {

        echo "क्षितिज जसे दिसते";

    } elseif (is_category('happenings') || has_category('happenings',$post->ID)) {

        echo "Happenings";

    } elseif (is_product() && is_product_category( 'music' ) ) {

        echo "music";

    } elseif (is_product_category( 'album' )) {

        echo "albums";

    } elseif ( is_product() && is_product_category( 'workshop' ) ) {
        echo "Workshop";
    } elseif( is_product() && has_term( 'workshop' ) ) {
        echo "Workshop";
    } else {
        the_title();
    }

    ?>

</h1>

I want to echo out Workshop in h1 if the product page is single product page AND if that product is in the workshop category. Same for Music. is_product_category works only on category page not on single product page.

How do I determine the category of single product and echo the relevant text. Other if statements (is_category('english') has_category()) are working except for the woocommerce pages?

1 个答案:

答案 0 :(得分:4)

您的代码中有一些关于WooCommerce类别的错误:

  • 功能 is_category() has_category() 不适用于WooCommerce产品类别(WooCommerce产品类别是自定义分类标准'<强> product_cat ')
  • 条件is_product() && is_product_category()无法与 && 一起使用,因为is_product()将定位单个产品页面,is_product_category()将定位产品类别档案页面

要在单个产品页面中定位您的产品类别,您需要使用带有“ product_cat ”分类标准的Wordpress条件函数has_term()
您还可以定位产品类别在您的条件下同时归档页面,如果它们使用相同的标题...

因此,您的代码(适用于WooCommerce产品类别)将类似于:

<h1 class="page-title"><?php

//      ... / ...

    if ( is_product() && has_term( 'music', 'product_cat' ) || is_product_category( 'music' ) ) {
        echo "Music";
    } elseif ( is_product() && has_term( 'album', 'product_cat' ) || is_product_category( 'album' ) ) {
        echo "Albums";
    } elseif( is_product() && has_term( 'workshop', 'product_cat' ) || is_product_category( 'workshop' ) ) {
        echo "Workshop";
    } else {
        the_title();
    }
?></h1>

如果您不需要同时定位产品类别归档页面,则必须在每个条件语句中删除 || is_product_category() ...