Set the highest priced variation as default in Woocommerce variable products
我的 woocommerce 安装中有很多不同的产品。
当用户浏览到任何产品页面时,它们都不会被预选为默认值。
手动选择它们将是一项乏味的工作。此外,每天都会使用 SQL 脚本自动导入新产品和变体。
我想为任何浏览到任何产品页面的用户预先选择价格最高的产品变体,其中包含可变产品。
怎么做?
- 你用 PHP 代码做输入?
- :) 是的,这绝对是一个选择。另一种选择是运行 sql 命令。有没有人有这样的脚本样本?
这是一个自动化解决方案,每次客户调用/浏览可变产品时都会完成这项工作。
可变产品将更新为具有最高价格的默认变体。
每次更新可变产品时,我都会设置一个自定义的帖子元键/值,这将只执行一次。
代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
add_action( ‘template_redirect’, ‘set_default_variation_job’ );
function set_default_variation_job() { if ( ! is_product() || is_admin() ) return; global $wpdb, $post; // Get an instance of the WC_Product object // Check if default variation has been updated, if yes we exit // Only for variable products $max_price = $product->get_variation_price(‘max’, true); // Get Max variation price // SQL Query: Get the variation ID of the max variation price // Get an instance of the WC_Product_Variation object // Loop through this variation attributes and format them // Set the default variation attributes in the Variable product |
代码进入您的活动子主题(活动主题)的 function.php 文件中。
经过测试并且可以工作。
- 首先,感谢您的代码。有用!其次,这是我的错误。我没有复制你的一段代码,当然它没有用。我的巴斯。再次感谢你。 @LoicTheAztec
转到文件 woocommerce/templates/single-product/add-to-cart/variable.php
并添加以下行:
1
|
‘selected’ => $options[0],
|
到函数wc_dropdown_variation_attribute_options()。
这将预先选择产品显示页面上的第一个变体。
- 这可行,但是否可以将其作为 functions.php 片段来代替?
- 不幸的是,这不起作用。我也在寻找相反的(最低)。有办法吗?
来源:https://www.codenong.com/48800869/