nhatimme nhatimme - 2 years ago 166
PHP Question

Display second min variation price of a variable Product in WooCommerce 3

I'm using the following script:

add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);

function custom_variation_price( $price, $product ) {

$price = '';

if ( !$product->min_variation_price || $product->min_variation_price !== $product->max_variation_price ) {
$price .= '<span style="display:none;" class="not-from">v.a. ' . _x('', 'min_price', 'woocommerce') . ' </span>';

$price .= woocommerce_price($product->get_price());
}

return $price;
}


It does show the min variation price at this moment. I want to create the following:


  • If the min price is 0,00, then show the 2nd product variation price.



E.g.: Product X has 3 different variations: 1 (€0,00), 2 (€5,00), 3 (€15,00). If the variation price is 0,00, then show second price variation, €5,00.

Answer Source

Here is the way to display the 2nd min variable price whenthe min price is equal to 0:

add_filter('woocommerce_variable_price_html', 'custom_variation_price_html', 10, 2);
function custom_variation_price_html( $price, $product ) {

    // Get all variations prices
    $prices = $product->get_variation_prices( true );

    // Get the prices (min and max)
    $min_price = current( $prices['price'] );
    $max_price = end( $prices['price'] );

    // Get 2nd min price
    $min_price2_arr = array_slice($prices['price'], 1, 1);
    $min_price2 = $min_price2_arr[0];

    if ( $min_price > 0) {
        $price = wc_price( $min_price );
    } elseif ( $min_price == 0 ) {
        $price = wc_price( $min_price2 );
    }
    return $price;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This is code tested and works only in WooCommerce 3+.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download