设置 WooCommerce 产品的价格范围,无需设置变量

Amb*_*ber 2 php wordpress custom-fields woocommerce price

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

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

例如,我想将其替换为$45 - $120 (不设置可变产品),而不是实际价格$45

任何帮助将非常感激。

Loi*_*tec 7

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

\n\n

然后,仅当最大范围字段设置了价格时,它才会在前端、商店、档案和单个产品页面上显示价格范围。

\n\n

代码:

\n\n
// Add a custom field for price range to product in backend\nadd_action( \'woocommerce_product_options_pricing\', \'add_field_product_options_pricing\' );\nfunction add_field_product_options_pricing() {\n    global $post;\n\n    echo \'<div class="options_group show_if_simple">\';\n\n    woocommerce_wp_text_input( array(\n        \'id\'            => \'_max_price_for_range\',\n        \'label\'         => __(\'Max price for range\', \'woocommerce\').\' (\'.get_woocommerce_currency_symbol().\')\',\n        \'placeholder\'   => __(\'Set the max price for range\', \'woocommerce\'),\n        \'description\'   => __(\'Set the max price for range, to activate it\xe2\x80\xa6\', \'woocommerce\'),\n        \'desc_tip\'      => \'true\',\n    ));\n\n    echo \'</div>\';\n}\n\n// Save product custom field to database when submitted in Backend\nadd_action( \'woocommerce_process_product_meta\', \'save_product_options_custom_fields\', 30, 1 );\nfunction save_product_options_custom_fields( $post_id ){\n    // Saving custom field value\n    if( isset( $_POST[\'_max_price_for_range\'] ) ){\n        update_post_meta( $post_id, \'_max_price_for_range\', sanitize_text_field( $_POST[\'_max_price_for_range\'] ) );\n    }\n}\n\n// Frontend: display a price range when the max price is set for the product\nadd_filter( \'woocommerce_get_price_html\', \'custom_range_price_format\', 10, 2 );\nfunction custom_range_price_format( $price, $product ) {\n\n    // Only for simple product type\n    if( $product->is_type(\'simple\') ){\n        // Get the max price for range\n        $max_price = get_post_meta( $product->get_id(), \'_max_price_for_range\', true );\n\n        if( empty($max_price) )\n            return $price; // exit\n\n        $active_price = wc_get_price_to_display( $product, array( \'price\' => $product->get_price() ) );\n\n        $price = sprintf( \'%s &ndash; %s\', wc_price($active_price), wc_price($max_price) );\n    }\n    return $price;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。

\n\n

在后台产品选项设置中:

\n\n

在此输入图像描述

\n\n

前端产品:

\n\n

在此输入图像描述

\n