在 Woocommerce 单个产品页面中更改并保存产品价格

Change and save the product price in Woocommerce single product pages

我有这个函数,它会在页面加载时触发。它检查 post 类型是否为 'product',在这种情况下我需要更改产品价格并保存页面。

我工作正常,但我需要知道如何设置新产品价格。

function changeAndSave( $array ) { 

    $post_type = get_post_type();
    if ($post_type == "product"){

        /*GET THE PRODUCT*/
        global $product;
        $product_id=$product->id;

        /*GET CURRENT PRICE*/
        $currentPrice=$product->get_price_html();

        /*SET NEW PRICE*/
        /* HERE.... ¿¿ how do I set my new price */
        $newPrice = 100€;

        /*SAVE THE PRODUCT*/    
        $product = wc_get_product($product_id);
        $product->save();
    }
}; 

// add the action 
add_action( 'loop_start', 'changeAndSave', 10, 1 ); 

更新:我试过了,但没有用:

function changeAndSave( $array ) { 

    $post_type = get_post_type();
    if ($post_type == "product"){

        /*GET THE PRODUCT*/
        global $product;
        $product_id=$product->id;
        $product = wc_get_product($product_id);

        /*GET CURRENT PRICE*/
        $currentPrice=$product->get_price_html();

        /*SET NEW PRICE*/
        $newRegularPrice = 81;
        $product->set_regular_price($newRegularPrice);

        /*SAVE THE PRODUCT*/    
        $product->save();
    }
}; 

// add the action 
add_action( 'loop_start', 'changeAndSave', 10, 1 ); 

您可以在代码中使用给定的产品 ID 尝试此代码块。

要更新常规价格:

update_post_meta($productID, '_regular_price', $newRegularPrice);

要更新促销价:

update_post_meta($productID, '_sale_price', $newSalePrice);

更新 - 根据您的评论:

如果是简单产品:

$product->set_regular_price( $newRegularPrice );
$product->set_price( $newRegularPrice );

如果是变体产品,使用"update_post_meta"函数。

您也可以查看:

1 -

2 -

已更新

首先,您没有为此使用正确的挂钩,因为它需要在页面加载之前触发。

尝试以下操作(对于简单产品):

add_action( 'template_redirect', 'change_and_save_product_price' );

function change_and_save_product_price() {
    if ( get_post_type() === "product" ){ // or use: is_product()
        // HERE your new product price
        $new_price = 100;

        // Get an instance of the WC_Product Object
        $product = wc_get_product( get_the_id() );

        if ( $product->is_type('simple') ) {
            // Get current price (if needed)
            // $price = $product->get_price();

            // Set the new price
            $product->set_regular_price( $new_price );
            $product->set_price( $new_price );

            // (optionally) reset sale price => uncomment below
            // $product->set_sale_price( false );

            // Save to database refresh refresh caches
            $product->save();
        }
    }
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。