Justin
Justin

Reputation: 21

Custom product price suffix based on product in WooCommerce

I need help to be able to display a different price suffix per product. Currently I have found code that displays price suffix according to categories but it doesn’t solve the issue as I need it be different for some products in the same categories.

The Custom product price suffix for selected product categories in WooCommerce answer code is based on categories. Can it be altered only for specific products instead?

Upvotes: 1

Views: 418

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29650

Just in case someone is wondering how this can be applied based on the already existing code.

in_array - Checks if a value exists in an array

function filter_woocommerce_get_price_html( $price, $product ) {
    // Set specfic product ID's
    $specific_product_ids = array( 1, 2, 3 );

    // Checks if a value exists in an array
    if ( in_array( $product->get_id(), $specific_product_ids ) ) {
        $price .= ' ' . __( 'per kg', 'woocommerce' );
    }

    return $price;
}
add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 );

To deal with multiple suffixes, you could use PHP: switch

function filter_woocommerce_get_price_html( $price, $product ) {
    // Get product ID
    $product_id = $product->get_id();
    
    // Set product ID's kg
    $product_ids_kg = array( 30, 813, 815 );
    
    // Set product ID's g
    $product_ids_g = array( 817, 819, 821 );
    
    // Checks if a value exists in an array 
    switch ( $product_id ) {
        case in_array( $product_id, $product_ids_kg ):
            $suffix = ' per kg';
            break;
        case in_array( $product_id, $product_ids_g ):
            $suffix = ' per 500g';
            break;
        default:
            $suffix = '';
    }

    // Return
    return $price . __( $suffix, 'woocommerce' );
}
add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 );

Upvotes: 1

Related Questions