gpt4 book ai didi

php - 在不设置变量的情况下设置 WooCommerce 产品的价格范围

转载 作者:行者123 更新时间:2023-12-01 22:07:49 37 4
gpt4 key购买 nike

在 woocommerce 中,我希望能够在不设置可变产品的情况下为我的简单产品设置价格范围,因为我不需要它。

请参阅以下链接:https://www.tnbloom.com.au/product/memorial-wreath/

例如,我想用 $45 - $120 代替实际价格 $45 (不设置变量产品).

如有任何帮助,我们将不胜感激。

最佳答案

以下代码将在产品选项定价设置中添加自定义价格字段,以设置显示价格范围的最高价格。因此,您必须为每种产品设置最高价格。

然后它将在前端、商店、文件和单个产品页面上显示价格范围,前提是最大范围字段为其设置了价格。

代码:

// Add a custom field for price range to product in backend
add_action( 'woocommerce_product_options_pricing', 'add_field_product_options_pricing' );
function add_field_product_options_pricing() {
global $post;

echo '<div class="options_group show_if_simple">';

woocommerce_wp_text_input( array(
'id' => '_max_price_for_range',
'label' => __('Max price for range', 'woocommerce').' ('.get_woocommerce_currency_symbol().')',
'placeholder' => __('Set the max price for range', 'woocommerce'),
'description' => __('Set the max price for range, to activate it…', 'woocommerce'),
'desc_tip' => 'true',
));

echo '</div>';
}

// Save product custom field to database when submitted in Backend
add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );
function save_product_options_custom_fields( $post_id ){
// Saving custom field value
if( isset( $_POST['_max_price_for_range'] ) ){
update_post_meta( $post_id, '_max_price_for_range', sanitize_text_field( $_POST['_max_price_for_range'] ) );
}
}

// Frontend: display a price range when the max price is set for the product
add_filter( 'woocommerce_get_price_html', 'custom_range_price_format', 10, 2 );
function custom_range_price_format( $price, $product ) {

// Only for simple product type
if( $product->is_type('simple') ){
// Get the max price for range
$max_price = get_post_meta( $product->get_id(), '_max_price_for_range', true );

if( empty($max_price) )
return $price; // exit

$active_price = wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) );

$price = sprintf( '%s &ndash; %s', wc_price($active_price), wc_price($max_price) );
}
return $price;
}

代码进入事件子主题(或事件主题)的 function.php 文件。经过测试并有效。

在后端产品选项设置中:

enter image description here

前端产品:

enter image description here

关于php - 在不设置变量的情况下设置 WooCommerce 产品的价格范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50502449/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com