如果您需要随时从标准价格中添加或删除金额,可以在WooCommerce的设置页面中添加自定义字段,然后使用内置过滤器修改产品的价格。
下面是我的做法:(这将放在你的主题中functions.php
文件)
/**
* Add a new tab to WooCommerce settings pages
**/
function add_wc_settings_tabs( $settings_tabs ) {
$settings_tabs[ \'modify-price\' ] = __( \'Modify Price\', \'woocommerce\' );
return $settings_tabs;
}
add_filter( \'woocommerce_settings_tabs_array\', \'add_my_wc_settings_tabs\', 60 );
/**
* Set up settings fields
**/
function get_my_custom_settings() {
return array(
array(
\'title\' => __( \'Amount to add\', \'woocommerce\' ),
\'desc\' => \'<br/>\' . __( \'Enter an amount to add to each product price\', \'woocommerce\' ),
\'id\' => \'price_modification_amount\',
\'type\' => \'number\',
\'min\' => \'0\',
\'step\' => \'.01\',
\'append\' => \'€\',
),
);
}
/**
* Outputs settings fields on the Modify Price settings tab
**/
function my_custom_settings_page() {
woocommerce_admin_fields( apply_filters( \'wc_get_settings_modify-price\', get_my_custom_settings() );
}
add_action( \'woocommerce_settings_modify-price\', \'my_custom_settings_page\' );
/**
* Update fields in database when page saved
**/
function update_my_custom_settings() {
woocommerce_update_options( get_my_custom_settings() );
}
add_action( \'woocommerce_update_options_modify-price\', \'update_my_custom_settings\' );
添加这些功能后,您将能够在WooCommerce>设置中新创建的“修改价格”选项卡下设置金额。
最后,要根据此金额调整价格,请再次将此函数添加到functions.php
:
/**
* Modify price HTML if a modification is set in Settings
**/
function my_custom_price_html( $output, $product ) {
$adjustment = get_option(\'price_modification_amount\');
if ( $adjustment ) {
$output = wc_price( wc_get_price_to_display( $product ) + $adjustment;
}
return $output;
}
add_filter( \'woocommerce_get_price_html\', \'my_custom_price_html\', 30, 2 );
/**
* Update price in cart if modification set in Settings
**/
function modify_cart_item_price( $cart_item ) {
$adjustment = get_option(\'price_modification_amount\');
if ( $adjustment ) {
$price = $cart_item[\'data\']->get_price() + $adjustment;
$cart_item[\'data\']->set_price( $price );
$cart_item[\'my_price\'] = $price;
}
return $cart_item;
}
add_filter( \'woocommerce_add_cart_item\', \'modify_cart_item_price\', 30, 1 );
/**
* Set correct price when reading cart from session
**/
function get_my_cart_item_from_session( $cart_item, $values, $cart_item_key ) {
if ( ! empty( $cart_item[\'my_price\'] ) ) {
$cart_item[\'data\']->set_price( $cart_item[\'my_price\'] );
}
return $cart_item;
}
add_filter( \'woocommerce_get_cart_item_from_session\', \'get_my_cart_item_from_session\', 30, 3 );