0

I need to create an additional "Add to Cart" button on the product page. In a simple product there is no problem with this. It is more difficult in a product with variants. To create such a button I need to know the ID of the default variant.

$product->get_default_attributes();

returns only the attribute name and value, no ID.

How to get the ID of the default variant in php code?

1 Answer 1

0

Try this code

add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);
function custom_variation_price( $price, $product ) {
    $available_variations = $product->get_available_variations();
    $selectedPrice = '';
    $dump = '';

    foreach ( $available_variations as $variation )
    {
        // $dump = $dump . '<pre>' . var_export($variation['attributes'], true) . '</pre>';

        $isDefVariation=false;
        foreach($product->get_default_attributes() as $key=>$val){
            // $dump = $dump . '<pre>' . var_export($key, true) . '</pre>';
            // $dump = $dump . '<pre>' . var_export($val, true) . '</pre>';
            if($variation['attributes']['attribute_'.$key]==$val){
                $isDefVariation=true;
            }   
        }
        if($isDefVariation){
            $price = $variation['display_price'];         
        }
    }
    $selectedPrice = wc_price($price);

//  $dump = $dump . '<pre>' . var_export($available_variations, true) . '</pre>';

    return $selectedPrice . $dump;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.