How to get current variation data inside raw_woocommerce_price hook?

I’d like to get current variation data inside the raw_woocommerce_price hook.

function filter_raw_woocommerce_price( $price_1 ) {
    global $product;

    // Some custom code to change price by variation factor
    $variation_id = product->Something_I_Need_To_Know_To_Get_Current_Variation();

    // bla bla bla
    $factor = PutSomeCustomCalculationHere($variation_id);
    $price_1 = $price_1 * $factor;

    return $price_1;
};

add_filter( 'raw_woocommerce_price', 'filter_raw_woocommerce_price', 10, 1 );

How can I achieve that?

Read More

Thank you

Related posts

2 comments

  1. use this code, if the product is ok type use your custom logic like this:

    add_filter( 'raw_woocommerce_price', array( $this, 'asdfasdadf' ) );
    function asdfasdadf($price){
        global $product;
        // check if that is var product
        if( ! $product->is_type( 'variable' ) ) return $price;
        // get variable data!
        var_dump( $product->get_attributes() ); exit;
    }
    
  2. ‘raw_woocommerce_price’ was not the hook that I need.

    Using instead these hooks was the way to go.

    Why? Because these hooks have the product’s instance as the second parameter. There, it got all information I need to got further.

    add_filter('woocommerce_get_price', 'return_custom_price', $product, 10, 2 );
    add_filter('woocommerce_get_regular_price', 'return_custom_price', 10, 2 );
    add_filter('woocommerce_get_sale_price', 'return_custom_price', 10, 2 );
    function return_custom_price($price, $product) {
        global $post, $woocommerce;
    
        if( ! $product->product_type == 'variable'  ) return $price;
    
        switch (@$product->variation_data['attribute_pa_support']) {
            case "pdf" :
                return ($price * 0.5);
            break;
        }
    
        return $price;
    
    }
    

Comments are closed.