预计阅读时间: 4 分钟

今天我们来看看WooCommerce的“添加到购物车”按钮。如果要根据产品类别更改“添加到购物车”文本怎么办?例如,您可能想对书籍显示“立即购买”,而对CD则显示“添加到购物篮”。

WooCommerce代码段:按产品类别更改“添加到购物车”文本(仅2个类别)


add_filter( 'woocommerce_product_add_to_cart_text', 'bbloomer_archive_custom_cart_button_text' );
 
function bbloomer_archive_custom_cart_button_text() {
global $product;       
if ( has_term( 'category1', 'product_cat', $product->ID ) ) {           
return 'Category 1 Add Cart';
} else {
return 'Category 2 Buy Now';
}
}

WooCommerce代码段:按产品类别更改“添加到购物车”文本(多个类别)


add_filter( 'woocommerce_product_add_to_cart_text', 'bbloomer_archive_custom_cart_button_text' );
  
function bbloomer_archive_custom_cart_button_text() {
global $product;
 
$terms = get_the_terms( $product->ID, 'product_cat' );
 foreach ($terms as $term) {
            $product_cat = $term->name;
            break;
}
 
switch($product_cat)
{
    case 'category1';
        return 'Category 1 button text'; break;
    case 'category2';
        return 'Category 2 button text'; break;
// case 'category3'; etc...
// return 'Category 3 button text'; break;
 
    default;
        return 'Default button text when no match found'; break;
}
}
此文章对你有帮助吗? 已有 0 人说这篇文章是有用的。