I am changing the text of the Add to cart button on shop pages in WooCommerce for specific products:
JavaScript
x
add_filter( 'woocommerce_product_add_to_cart_text', 'add_to_cart_text' );
function add_to_cart_text( $default ) {
if ( get_the_ID() == 1 ) {
return __( 'Text1', 'your-slug' );
} elseif ( get_the_ID() == 2 ) {
return __( 'Text2', 'your-slug' );
} elseif ( get_the_ID() == 3) {
return __( 'Text3', 'your-slug' );
} else {
return $default;
}
}
If I have two or more IDs that need to have the same button text, how can I add an array of these ids into my function?
Advertisement
Answer
You can use in_array()
PHP conditional function like:
JavaScript
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_text', 10, 2 );
function custom_add_to_cart_text( $text, $product ) {
if ( in_array( $product->get_id(), array(1) ) ) {
$text = __( 'Text1', 'text-domain' );
} elseif ( in_array( $product->get_id(), array(2) ) ) {
$text = __( 'Text2', 'text-domain' );
} elseif ( in_array( $product->get_id(), array(3, 4) ) ) {
$text = __( 'Text3', 'text-domain' );
}
return $text;
}
It should work.
Also you should use $product
missing arguments in your hooked function.