Everything works good if I remove the && $product->is_type( 'variable' )
However, when I add that line, the first if, doesn’t seem to work. What am I doing wrong?
Expecting: If product is in category “farsk-ved” and is a variable product, the text should be “Välj längd”. So all the single products, should go to the “else” section (“Köp”).
What is happening: All products, except the “elseif” part, is getting “köp”.
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_loop_add_to_cart_button', 20, 2 );
function custom_loop_add_to_cart_button( $button_text ) {
// BELOW set the product categoty slug and the product ID
$product = new WC_Product( get_the_ID() );
if ( has_term( 'farsk-ved', 'product_cat') && $product->is_type( 'variable' )) {
$button_text = __("Välj längd", "woocommerce");
}
elseif ( has_term( 'torr-ved', 'product_cat') ) {
$button_text = __("Välj mängd", "woocommerce");
}
else {
$button_text = __("Köp", "woocommerce");
}
return $button_text;
}
3
Answers
So the solution was to replace
$product = new WC_Product( get_the_ID() );
withglobal $product;
If you use
$product = new WC_Product( get_the_ID() );
and$product->is_type( 'variable' )
it will return bool(false)If you use
$product = new WC_Product( get_the_ID() );
and$product->get_type()
it will return simple for all products including variable type.So you just need to use like this,
I think this will help.
The real way: the
WC_Product
Object is directly included forwoocommerce_product_add_to_cart_text
filter hook as 2nd argument (and missing from your function code):Tested and works.