skip to Main Content

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


  1. Chosen as BEST ANSWER

    So the solution was to replace $product = new WC_Product( get_the_ID() ); with global $product;


  2. 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,

    $product = new WC_Product_Variable($product_id);
    if ( has_term( 'farsk-ved', 'product_cat') && $product->get_type()=='variable') {
    

    I think this will help.

    Login or Signup to reply.
  3. The real way: the WC_Product Object is directly included for woocommerce_product_add_to_cart_text filter hook as 2nd argument (and missing from your function code):

    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, $product ) { // <== the missing argument 
        // BELOW set the product category Id, slug or name
        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;
    }
    

    Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search