重命名WooCommerce 3中缺货产品的“添加到购物车"按钮 [英] Rename Add to Cart buttons for Out Of Stock Products in WooCommerce 3
问题描述
当WooCommerce中的产品售罄时,我想将 'Add to Cart'
重命名为 'Sold Out'
.
I would like to rename 'Add to Cart'
to 'Sold Out'
when product is sold out in WooCommerce.
这是我的代码:
add_filter( 'add_to_cart_text', 'woo_custom_single_add_to_cart_text' );
add_filter( 'woocommerce_product_single_add_to_cart_text',
'woo_custom_single_add_to_cart_text' ); // 2.1 +
function woo_custom_single_add_to_cart_text() {
if( $product->get_stock_quantity() == 0 )
return __( 'Sold Out', 'woocommerce' );
} else {
return __( 'Add to cart ', 'woocommerce' );
}
但是它不起作用.
我做错了吗?
推荐答案
更新(现在使用可变产品和变体)
UPDATE (Working now with variable products and variations)
您的代码中有一些错误:
There is some errors in your code:
1.您需要在函数中将 hooks参数设置为 $button_text
和 $product
.
2.已弃用 add_to_cart_text
,并替换为 woocommerce_product_add_to_cart_text
.
1.You need to to set the hooks arguments in your function as $button_text
and $product
.
2.The add_to_cart_text
is deprecated and replaced by woocommerce_product_add_to_cart_text
.
在此更新的代码中,我添加了一个jQuery脚本,该脚本仅捕获变量产品(在单个产品页面上)的所选变体并更改按钮文本.现在,这适用于所有情况.
In this updated code I have added a jQuery script that catch the selected variation for variable products only (on single product pages) and to change the button text. Now this is working for all cases.
add_filter( 'woocommerce_product_add_to_cart_text', 'customizing_add_to_cart_button_text', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'customizing_add_to_cart_button_text', 10, 2 );
function customizing_add_to_cart_button_text( $button_text, $product ) {
$sold_out = __( "Sold Out", "woocommerce" );
$availability = $product->get_availability();
$stock_status = $availability['class'];
// Only for variable products on single product pages
if ( $product->is_type('variable') && is_product() )
{
?>
<script>
jQuery(document).ready(function($) {
$('select').blur( function(){
if( '' != $('input.variation_id').val() && $('p.stock').hasClass('out-of-stock') )
$('button.single_add_to_cart_button').html('<?php echo $sold_out; ?>');
else
$('button.single_add_to_cart_button').html('<?php echo $button_text; ?>');
console.log($('input.variation_id').val());
});
});
</script>
<?php
}
// For all other cases (not a variable product on single product pages)
elseif ( ! $product->is_type('variable') && ! is_product() )
{
if($stock_status == 'out-of-stock')
$button_text = $sold_out.' ('.$stock_status.')';
else
$button_text.=' ('.$stock_status.')';
}
return $button_text;
}
代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.
此代码已经过测试并且可以正常工作
This code is tested and works
这篇关于重命名WooCommerce 3中缺货产品的“添加到购物车"按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!