简体   繁体   English

WooCommerce-如果单个产品页面上的产品类别声明

[英]WooCommerce - If product category statement on single product page

Im trying to do an if statement on single product page to echo a link based on product category product category. 我试图在单个产品页面上执行if语句,以基于产品类别产品类别回显链接。

I know i can't use is_product_category() outside of category archive pages. 我知道我不能在类别存档页面之外使用is_product_category() So i've tried using has_term But it's just not echoing what i want. 因此,我尝试使用has_term但这只是没有回应我想要的。 Here's the code i'm using so far. 这是我到目前为止使用的代码。

<?php if( has_term( array( 'mac', 'imac', 'macbook', 'imac-pro' ), 'product_cat' ) ) {
    echo '<a href="#">All Mac Accessories</a>';
} ?>

What am i missing here? 我在这里想念什么?

It seems the has_term needs a post id in the third parameter. 似乎has_term在第三个参数中需要一个帖子ID。 It doesn't automatically take the third parameter as the current post id. 它不会自动将第三个参数用作当前帖子ID。 You have to manually pass the the current post id. 您必须手动传递当前帖子ID。 By default, null is passed in the third parameter according to the documentation. 默认情况下,根据文档,在第三个参数中传递null。

Check it out here, https://developer.wordpress.org/reference/functions/has_term/ 在这里查看, https://developer.wordpress.org/reference/functions/has_term/

I have the tested the following code in the content-single-product.php and it works perfectly. 我已经在content-single-product.php中测试了以下代码,它可以完美运行。

<?php 
    $terms = ['sagar', 'tamang'];
    if ( has_term( $terms, 'product_cat', get_the_ID() ) ) {
       echo '<h1>Yes</h1>';
    } else {
        echo '<h1>No</h1>';
    }

?>

You can modify your code as following. 您可以按以下方式修改代码。

<?php
    if( has_term( array( 'mac', 'imac', 'macbook', 'imac-pro' ), 'product_cat', get_the_ID() ) ) {
        echo '<a href="#">All Mac Accessories</a>';
    } 
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM