I want to be able to display a specific Add To Card Text for each single product, if set.
There are some plugins out there, but they "just" cover Add To Card Text for categories or product types. That's why I tried this way using a Custom Field.
So I wrote this code directly in a template file. This code works, but is it good, safe, at the right place?
// file: /woocommerce-templates/single-product/add-to-cart/simple.php
<button "..." >
<?php
$text = get_post_meta($product->get_id(), 'add_to_cart_text', true);
if ($text) {
echo esc_html($text);
} else {
echo esc_html($product->single_add_to_cart_text()); // this line is default
}
?>
</button>
I would use this instead:
<?php
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_button_text', 20, 2 );
function custom_add_to_cart_button_text( $button_text, $product ) {
$custom_button_text = get_post_meta( $product->get_id(), 'add_to_cart_text', true );
// If there is custom text set for this product, then display it instead of the default text.
if ( ! empty( $custom_button_text ) ) {
$button_text = __( $custom_button_text, 'text-domain' );
}
return $button_text;
}
Paste it in your functions.php