WooCommerce插件内部条件标签

时间:2019-12-08 作者:Nathan Wilson

我正在编写一个小插件,在WooCommerce产品页面的“添加到购物车”按钮上方添加一些文本。

我的代码:

add_action(\'woocommerce_before_add_to_cart_button\', \'ddd_above_add_to_cart\', 100);
function ddd_above_add_to_cart() { 
    if(is_product_category(\'vss\') ) {
        echo \'hello world\';
        }
}
我的问题是当我使用条件标记时is_product_category(\'vss\') 根据产品类别显示文本。我确信这个错误是由于函数没有在循环中运行而发生的,但我不确定如何更改它。

有人能帮我吗?

1 个回复
最合适的回答,由SO网友:metalbox 整理而成

此功能在产品页中不起作用

is_product_category()
因此,对我来说,最好的选择是首先获取当前帖子的条款,然后再获取名称或slug,在这种情况下,我选择了类别名称

$product_cat_name = $term->name;
但是你也可以选择slug(更好的选择)

$product_cat_slug = $term->slug; 
这里是文档https://developer.wordpress.org/reference/functions/get_the_terms/

类别名称示例

/*Write here your own functions */
    add_action(\'woocommerce_before_add_to_cart_button\', \'ddd_above_add_to_cart\', 100);
    function ddd_above_add_to_cart() { 

            global $post;
            $terms = get_the_terms( $post->ID, \'product_cat\' );
            $nterms = get_the_terms( $post->ID, \'product_tag\'  );
            foreach ($terms  as $term  ) {
                $product_cat_id = $term->term_id;
                $product_cat_name = $term->name;
                break;
            }      
           //compare current category name == any category name you want
            if($product_cat_name ==\'vss\' ) {
                echo "This Work";
            }           
    }
类别Slug示例

/*Write here your own functions */
    add_action(\'woocommerce_before_add_to_cart_button\', \'ddd_above_add_to_cart\', 100);
    function ddd_above_add_to_cart() { 

            global $post;
            $terms = get_the_terms( $post->ID, \'product_cat\' );
            $nterms = get_the_terms( $post->ID, \'product_tag\'  );
            foreach ($terms  as $term  ) {
                $product_cat_id = $term->term_id;
                $product_cat_name = $term->name;
                $product_cat_slug = $term->slug;
                break;
            }      

            //compare current category slug == any category slug you want
            if($product_cat_slug ==\'any-slug-category\' ) {
                echo "This Work";
            }           
    }

相关推荐