If you need to be able to add or remove an amount from standard prices at any time, you could add a custom field to WooCommerce’s settings pages, then modify the price of your products using the built-in filter.
Here is how I would do it: (this would go in your theme’s functions.php
file)
/**
* 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' );
Once you’ve added these functions, you will be able to set an amount in WooCommerce > Settings, under your newly created ‘Modify Price’ tab.
Finally, to adjust prices based on this amount, add this function, again, to 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 );