How to check for an array of product Ids in WooCommerce

Viewed 946

I am changing the text of the Add to cart button on shop pages in WooCommerce for specific products:

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?

3 Answers

You can use in_array() PHP conditional function like:

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.

If you want to do dynamic for future purposes then you can save your add_to_cart_text to custom fields and you can retrieve them in the woocommerce_product_add_to_cart_text hook. check below code.

add_filter( 'woocommerce_product_add_to_cart_text', 'add_to_cart_text', 10, 2 );
function add_to_cart_text( $default, $product ) {

    if( get_post_meta( $product->get_id(), 'add_to_cart_text', true ) != '' ){
        return get_post_meta( $product->get_id(), 'add_to_cart_text', true );
    }

    return $default;
}

save your add_to_cart_text to custom fileds here.

enter image description here

You can use in_array() function for that.

add_filter( 'woocommerce_product_add_to_cart_text', 'add_to_cart_text' );
function add_to_cart_text( $default ) {
    global $product;
    $number_array = array(1, 2, 3, 4);
    $number_second = array(5, 6, 7, 8);
    $number_third = array(9, 10, 11, 12);
    if ( in_array($product->get_id(), $number_array ) ) {
        return __( 'Text1', 'your-slug' );
    } elseif ( in_array($product->get_id(), $number_second ) ) {
        return __( 'Text2', 'your-slug' );
    } elseif ( in_array($product->get_id(), $number_third ) ) {
        return __( 'Text3', 'your-slug' );
    } else {
        return $default;
    }
}
Related