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

Output a custom shortcode for a specific product category in WooCommerce

我想在我的商店页面上为我的产品添加一个额外的按钮,但仅限于特定类别。我已经走到这一步了,但我似乎无法正确调用它。

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');
}

如能帮助指出我的错误,我们将不胜感激。

你的代码有很多错误

您需要在您的条件下以这种方式设置has_term()以使其工作:

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

对于产品 ID 也这样做:$product->get_id()...我也尝试更正其他错误...

所以你的代码应该是这样的:

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');
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

现在应该可以了……