Change Product Prices Using Hooks in WooCommerce 3
WooCommerce 3 introduced improved options for manipulating product prices using hooks, including those for variation prices. However, the hooks you've attempted may not be appropriate.
The recommended hooks for controlling product prices are:
Simple, Grouped, and External Products:
Variations:
Variable (Price Range):
Sales:
For variation prices, you'll also need to manage cached prices. The woocommerce_get_variation_prices_hash filter is efficient for this purpose.
To handle variations more effectively, consider the plugin version of the code provided below. It includes a constructor function and handles price caching.
// Plugin Version class MyPlugin { public function __construct() { // Simple, grouped, and external products add_filter('woocommerce_product_get_price', array($this, 'custom_price'), 99, 2); add_filter('woocommerce_product_get_regular_price', array($this, 'custom_price'), 99, 2); // Variations add_filter('woocommerce_product_variation_get_regular_price', array($this, 'custom_price'), 99, 2); add_filter('woocommerce_product_variation_get_price', array($this, 'custom_price'), 99, 2); // Variable (price range) add_filter('woocommerce_variation_prices_price', array($this, 'custom_variable_price'), 99, 3); add_filter('woocommerce_variation_prices_regular_price', array($this, 'custom_variable_price'), 99, 3); // Handling price caching add_filter('woocommerce_get_variation_prices_hash', array($this, 'add_price_multiplier_to_variation_prices_hash'), 99, 3); } // ...functionality as described in the original answer... } new MyPlugin();
For theme use, place the following code in your functions.php file:
// Theme Version // ...functionality as described in the original answer...
Remember, the use of display html hooks will not effectively change product prices. Additionally, consider the hooks for filtering product prices in widgets, which allow for setting minimum and maximum prices.
The above is the detailed content of How Can I Efficiently Change Product Prices in WooCommerce 3 Using Hooks?. For more information, please follow other related articles on the PHP Chinese website!