我有此功能,当页面加载时会触发。它检查帖子类型为“产品”,在这种情况下,我需要更改产品价格并保存页面。
我工作正常,但我需要知道如何设置新产品的价格。
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 );
更新
首先,您没有为此使用正确的钩子,因为它需要在页面加载之前被触发。
尝试以下操作(对于简单产品):
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文件中。经过测试和工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句