Wordpress 基于cookie数据的产品价格-WooCommerce
我有一个自定义的网站加载弹出窗口,并将所选选项存储在cookie中,我想根据所选选项更改产品的价格 我在产品中添加了基于这些选项的价格元框,用于简单和可变的产品 并在前端检索该价格,请检查以下代码:Wordpress 基于cookie数据的产品价格-WooCommerce,wordpress,dynamic,woocommerce,price,Wordpress,Dynamic,Woocommerce,Price,我有一个自定义的网站加载弹出窗口,并将所选选项存储在cookie中,我想根据所选选项更改产品的价格 我在产品中添加了基于这些选项的价格元框,用于简单和可变的产品 并在前端检索该价格,请检查以下代码: add_filter( 'woocommerce_product_get_price', 'return_price_by_option', 10, 2 ); function return_price_by_option( $price, $product ) { // option
add_filter( 'woocommerce_product_get_price', 'return_price_by_option', 10, 2 );
function return_price_by_option( $price, $product ) {
// options can be digits like 1, 2, 3, ...
$option = isset( $_COOKIE['option'] ) ? $_COOKIE['option'] : '';
if( $option ) {
$regMKey = '_sale_price_option_' . $option;
$optPrice = get_post_meta( $product->get_id(), $regMKey, true );
if( empty($optPrice) ) {
$regMKey = '_regular_price_option_' . $option;
$optPrice = get_post_meta( $product->get_id(), $regMKey, true );
}
return $optPrice;
}
return $price;
}
// Also used two more filter for regular and sale price,
// Function have same code, but just return the price for same meta key
add_filter( 'woocommerce_product_get_regular_price', 'return_regular_price_by_option', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'return_sale_price_by_option'), 10, 2 );
它适用于简单的产品,
但是,不为可变产品工作,有人能帮我了解可变产品吗?请建议任何简单的方法。添加以下代码片段以更改可变和变体产品的价格-
function return_price_by_option( $price, $product ) {
// delete product cache
wc_delete_product_transients( $product->get_id() );
// options can be digits like 1, 2, 3, ...
$option = isset( $_COOKIE['option'] ) ? $_COOKIE['option'] : '';
if( $option ) {
$regMKey = '_sale_price_option_' . $option;
$optPrice = get_post_meta( $product->get_id(), $regMKey, true );
if( empty($optPrice) ) {
$regMKey = '_regular_price_option_' . $option;
$optPrice = get_post_meta( $product->get_id(), $regMKey, true );
}
return $optPrice;
}
return $price;
}
// Variable
add_filter('woocommerce_product_variation_get_regular_price', 'return_price_by_option', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'return_price_by_option' , 99, 2 );
function return_price_by_option_variation( $price, $variation, $product ) {
// delete product cache
wc_delete_product_transients($variation->get_id());
// options can be digits like 1, 2, 3, ...
$option = isset( $_COOKIE['option'] ) ? $_COOKIE['option'] : '';
if( $option ) {
$regMKey = '_sale_price_option_' . $option;
$optPrice = get_post_meta( $product->get_id(), $regMKey, true );
if( empty($optPrice) ) {
$regMKey = '_regular_price_option_' . $option;
$optPrice = get_post_meta( $product->get_id(), $regMKey, true );
}
return $optPrice;
}
return $price;
}
// Variations
add_filter('woocommerce_variation_prices_price', 'return_price_by_option_variation', 99, 3 );
add_filter('woocommerce_variation_prices_regular_price', 'return_price_by_option_variation', 99, 3 );