[英]How to change add to cart button text for specific variable products on single page in WooCommerce
I have a few variable products on my website.我的网站上有一些可变产品。 Among those only on a few specific products, I have added two variations on those products one is "carbon fiber" and other is "unpainted" now what I want is when user clicks on 2nd variation which is "unpainted" the text of add to cart button should change from "add to cart" button to "made to order. I have updated my question to be more specific Below is the code First part code is jQuery to display the variations on my single product page and the second to change the name of variations for specific products:
在那些仅针对少数特定产品的产品中,我在这些产品上添加了两个变体,一个是“碳纤维”,另一个是“未上漆”,现在我想要的是当用户单击“未上漆”的第二个变体时添加的文本购物车按钮应从“添加到购物车”按钮更改为“定制”按钮。我已将我的问题更新为更具体 下面是代码 第一部分代码是 jQuery,用于在我的单个产品页面上显示变体,第二部分用于更改特定产品的变体名称:
window.addEventListener('load', (event) => {
var initialvalue=jQuery('#pa_choose-option').val();
if(initialvalue=="carbon-fibre")
jQuery('.single_variation_wrap .single_add_to_cart_button').html("Add To
Cart");
jQuery('#pa_choose-option').on('change', function() {
console.log("here");
var initialvalue=jQuery('#pa_choose-option').val();
if(initialvalue!="carbon-fibre")
jQuery('.single_variation_wrap .single_add_to_cart_button').html("Made
to Order");
else
jQuery('.single_variation_wrap .single_add_to_cart_button').html("Add To
Cart");
});
});
add_filter( 'woocommerce_product_single_add_to_cart_text',
'custom_addtocart_button_text', 10, 2 );
function custom_addtocart_button_text( $button_text, $product ) {
// 1st product
if ( $product->get_id() == 6577 ) {
$button_text = __( 'jawad', 'woocommerce' );
}
// 2nd product
elseif ( $product->get_id() == 6570 ) {
$button_text = __( 'kiani', 'woocommerce' );
}
return $button_text;
}
You can use show_variation
trigger.您可以使用
show_variation
触发器。 try the below code.试试下面的代码。
function change_add_to_cart_text_based_on_variation(){
global $post;
$specific_ids = array( 6594, 6577 );
if( is_product() && in_array( $post->ID, $specific_ids ) ){
?>
<script type="text/javascript">
(function($){
$( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) {
if( variation.attributes['attribute_pa_choose-option'] == 'unpainted' ){
jQuery('.single_variation_wrap .single_add_to_cart_button').html( "Made to Order" );
}else{
jQuery('.single_variation_wrap .single_add_to_cart_button').html( "Add To Cart" );
}
} );
$( document ).on('click', '.reset_variations', function(event) {
event.preventDefault();
jQuery('.single_variation_wrap .single_add_to_cart_button').html("Add To Cart");
});
})(jQuery);
</script>
<?php
}
}
add_action( 'wp_footer', 'change_add_to_cart_text_based_on_variation', 10, 1 );
Tested and works.测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.