根据 WooCommerce 产品类型更改添加到购物车按钮和文本

时间:2021-01-20 11:41:48

标签: php wordpress woocommerce product archive

如何在产品列表循环中更改 WooCommerce 添加到购物车按钮,但取决于产品类型,例如:

  1. 对于有变化的产品,我希望在“添加到购物车”按钮中添加一个文本:“显示产品”
  2. 对于简单的产品“显示产品”
  3. 对于缺货的产品:“不可用”

我尝试使用以下代码但不起作用:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product  ) {
    $button_text = __( "Out of stock", "woocommerce" );
    return '<a class="view-product" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
    if( ! $product->managing_stock() && ! $product->is_in_stock() ) {
        return $button;
    }
    if( $product->is_type( 'variable' ) ) return $button;
}

1 个答案:

答案 0 :(得分:3)

请尝试以下操作:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product  ) {
    // Out of stock products
    if( ! $product->is_in_stock() ) {
        $button_text = __( "Unavailable", "woocommerce" );
    }
    // Simple and Variable products
    elseif( $product->is_type( 'simple' ) || $product->is_type( 'variable' ) ) {
        $button_text = __( "Show product", "woocommerce" );
    } 
    // Other product types
    else {
        $button_text = add_to_cart_text(); 
    }
    
    return '<a class="view-product button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
}

代码位于活动子主题(或活动主题)的functions.php 文件中。它应该工作

相关问题