How do I get the Product ID in the filter ‘woocommerce_product_get_weight’?

The following code in my functions.php file and does indeed change the weight for all products but I would like to isolate it to a specific product.

add_filter('woocommerce_product_get_weight', 'rs_product_get_weight', 10, 1);
function rs_product_get_weight($weight) {
    $weight = 45.67;

    return $weight;
}

Is there any way to determine the product ID in my filter function?

Related posts

Leave a Reply

2 comments

  1. I am afraid to say it doesn’t work this way…
    if you look at woocommerce get_weight function

    public function get_weight() {
    
        return apply_filters( 'woocommerce_product_get_weight', $this->weight ? $this->weight : '' );
    }
    

    Maybe you are referencing to and old version of woocommerce…

    So, for example, if you want to change dinamically a cart product weight, you have to hook woocommerce_before_calculate_totals filter

    and add this function

    public function action_before_calculate( WC_Cart $cart ) {
    
            if ( sizeof( $cart->cart_contents ) > 0 ) {
    
                foreach ( $cart->cart_contents as $cart_item_key => $values ) {
    
                    $_product = $values['data'];
    
                    {
    
                    ////we set the weight
                    $values['data']->weight = our new weight;
    
                }
    
    
                }
            }
    }
    

    and so on…

  2. It’s a little strange, but product weight seems to come from the get_weight() method which has 2 filters inside of it. The one you are referencing and also woocommerce_product_weight which does indeed have the product ID also passed along.

    /**
     * Returns the product's weight.
     * @todo   refactor filters in this class to naming woocommerce_product_METHOD
     * @return string
     */
    public function get_weight() {
        return apply_filters( 'woocommerce_product_weight', apply_filters( 'woocommerce_product_get_weight', $this->weight ? $this->weight : '' ), $this );
    }
    

    Therefore you should be able to filter the weight with:

    add_filter('woocommerce_product_weight', 'rs_product_get_weight', 10, 2);
    function rs_product_get_weight($weight, $product) {
        if( $product->id == 999 ){
            $weight = 45.67;
        }
    
        return $weight;
    }