简体   繁体   English

输出WooCommerce中特定产品类别的自定义简码

[英]Output a custom shortcode for a specific product category in WooCommerce

I am trying to add an extra button to my products on my shop page but only to a specific category. 我试图在我的商店页面上为我的产品添加一个额外的按钮,但仅添加到特定类别。 I have gotten this far but I cannot seem to call it up right. 我已经走了这么远,但我似乎无法正确地称呼它。

if (!function_exists('add_accessory_button')){
function add_accessory_button() {
  global $product;
  $product_cat = $product->product_cat;

  if( has_term( 'dealqualify',$product_cat ) && in_the_loop() ) {
    $link = get_post_meta( $product->ID, ‘acc_link’, true );
    echo do_shortcode('<br>[button link="' . esc_attr($link) . '"]View Accessory[/button]');
} }
add_action('woocommerce_after_shop_loop_item','add_accessory_button');
}

Any help to pinpoint my mistake would be appreciated. 任何帮助查明我的错误的帮助将不胜感激。

There is a lot of errors in your code 您的代码中有很多错误

You need to set has_term() this way in your condition to make it work: 您需要在您的条件中以这种方式设置has_term()使其起作用:

has_term( 'dealqualify', 'product_cat', $product->get_id() )

Also for the product ID do it this way: $product->get_id() ... I have try to correct the others errors too... 对于产品ID,也可以这样: $product->get_id() ...我也尝试过纠正其他错误...

So your code should be something like: 因此,您的代码应类似于:

if ( ! function_exists('add_accessory_button')){

    function add_accessory_button() {
        global $product;
        if( has_term( 'dealqualify', 'product_cat', $product->get_id() ) && in_the_loop() ) {
            $link = get_post_meta( $product->get_id(), 'acc_link', true );
            echo '<br>' . do_shortcode("[button link='$link']View Accessory[/button]");
    }
    add_action('woocommerce_after_shop_loop_item','add_accessory_button');
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file. 代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。

This should work now… 现在应该可以工作了……

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

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