Skip to content
Advertisement

How to target an array of Product IDs in WooCommerce?

I’m using the code below to change a product price to text (Contact for Pricing) when the price field is left empty:

add_filter( 'woocommerce_get_price_html', 'change_special_product_price', 10, 2 );
function change_special_product_price( $price_html, $product ) {
    if ( $product->id == 6917 ) {
        $price_html = '<span class="woocommerce-Price-amount amount">Contact for Pricing</span>';
    }

    return $price_html;
}

add_filter('woocommerce_empty_price_html', 'custom_call_for_empty_price_html');
function custom_call_for_empty_price_html() {
    return 'TBC';
}

function dequeue_woocommerce_styles_scripts() {
    if ( function_exists( 'is_woocommerce' ) ) {
        if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
        }
    }
}

It works for one product, but I’m having trouble getting it to work for multiple products.

How do I target an array of product ids?

Advertisement

Answer

For an array of product IDs use in_array() conditional function as follows:

function change_special_product_price( $price_html, $product ) {
    $product_ids = array(6917, 6918, 6921);

    if ( in_array($product->get_id(), $product_ids ) ) {
        $price_html = '<span class="woocommerce-Price-amount amount">' . __("Contact for Pricing") . '</span>';
    } 
    return $price_html;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement