Wed*_*Wed 2 php wordpress woocommerce price product-variations
我的 WooCommerce 安装中有很多不同的产品。当用户浏览任何产品页面时,它们都不会被预先选择为默认值。
手动选择它们将是一项乏味的工作。此外,每天都会使用 SQL 脚本自动导入新产品和变体。
我希望为浏览到具有可变产品的任何产品页面的任何用户提供最高价格的预选产品变体。
那怎么办呢?
更新 - 2023 (代码简化和优化)
这是一种自动化解决方案,每次客户调用/浏览可变产品时,该解决方案都会完成一次工作。
可变产品将更新为具有最高价格的默认变体。
这只会完成一次,因为每次更新可变产品时我都会设置自定义后元键/值。
代码:
add_action( 'template_redirect', 'set_default_variation_job' );
function set_default_variation_job() {
if ( ! is_product() || is_admin() ) return;
$product_id = get_the_ID();
$product = wc_get_product($product_id); // Get the variable product object
if( ! is_a( $product, 'WC_Product' ) return; // Exit if is not a product object
// Only for variable products & Check if default variation has been updated
if ( $product->is_type( 'variable' ) && ! $product->get_meta('_default_variation_updated') ) {
$active_prices = $product->get_variation_prices()['price']; // Array of variation Id / active price pairs
$variations_ids = array_keys($active_prices); // Array of variations IDs
$variation_id = end($variations_ids); // Get the variation with the highest price
$variation = wc_get_product( $variation_id ); // Get an instance of the WC_Product_Variation object
$default_attributes = $variation->get_variation_attributes(false); // Get formatted variation attributes
// Set the default variation attributes in the Variable product
$product->set_default_attributes( $default_attributes );
// Set a meta data flag to avoid update repetitions
$product->update_meta_data('_default_variation_updated', '1');
$product->save(); // Save the data
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于子主题的functions.php 文件中(或插件中)。经过测试并有效。
相关:在 WooCommerce 中将折扣百分比最高的变体设置为默认值