Dears,
The following code works ok to change the Add to Cart text on single products when it is on Backorder enabled.
add_filter( 'woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_single_prod', 10, 2 );
function change_add_to_cart_single_prod( $text, $product ){
if ( $product->is_on_backorder( 1 ) ) {
return __( 'Reservar', 'woocommerce' );
}
return __( 'Comprar', 'woocommerce' );
}
But it does not work with variations unless the every variation is in backorders or out of stock. What may be the best way to change the Add to Cart button to a variations with Backorders allowed? I am guessing it has to be done with js.
When a product variation is selected, a hidden input field is set in the variation form with the id of the selected product variation. For example:
<input type="hidden" name="variation_id" class="variation_id" value="44">
If the selected attributes do not match any product variation, the value will be blank.
All possible product variations are in the data-product_variations
attribute of the variation form element.
Then you can use this jQuery script to change the button name. It will be Reservar if the product variation allows backorders while Comprar if it does not.
// change the text of the add to cart button based on product backorders
add_action( 'wp_footer', 'change_the_text_of_the_add_to_cart_button' );
function change_the_text_of_the_add_to_cart_button() {
?>
<script type="text/javascript">
jQuery(function($){
$('input[name=variation_id].variation_id').change(function(){
const variationID = $(this).val();
const variationData = $('form.variations_form').data("product_variations");
$(variationData).each(function(index,variation){
if ( variationID == variation.variation_id ) {
if ( variation.backorders_allowed ) {
$('form.variations_form button[type=submit]').text('Reservar');
} else {
$('form.variations_form button[type=submit]').text('Comprar');
}
}
});
});
});
</script>
<?php
}
The code has been tested and works. Add it to your active theme's functions.php.