在 woocommerce_before_calculate_totals 过滤器中获取产品 ID

get product id in woocommerce_before_calculate_totals filter

我正在尝试获取单击“添加到购物车”按钮的产品的产品 ID,以便我可以更改购物车中该产品的价格。全局产品对象不工作并显示 NULL。目前我有硬编码的产品 ID,即 $target_product_id = 48,这是我的代码

add_action( 'woocommerce_before_calculate_totals',array($this,'add_custom_price' )); 

function add_custom_price( $cart_object ) {

            $tac_dd_discounted_price = 10; 

            $target_product_id = 48;

            foreach ( $cart_object->cart_contents as $key => $value ) {
                if ( $value['product_id'] == $target_product_id ) {
                    $value['data']->price = $custom_price;
                }

            }

            /*global $woocommerce; 
            $woocommerce->cart->add_to_cart(48);*/

        }

如果设置,$_REQUEST['add-to-cart'] 应该会为您提供刚刚添加到购物车的产品的 ID。