在 Woocommerce 中显示正常价格或可变价格范围

Display normal price or variable price range in Woocommerce

我有一个产品列表,但在显示可变产品的价格范围时遇到了问题。

如您所见,价格是否为正常价格,一切正常。然而,如果产品有可变价格,则显示的价格为 0€

嗯,显示价格的代码是这样的:

<?php
if (isset($ebookstore_theme_option['woo-list-price']) && 
    $ebookstore_theme_option['woo-list-price'] == 'enable') {
    $ebookstore_woo .= '<strong class="amount">'.esc_attr($currency).''.$price_sale.'</strong>';
}

知道如何显示可变范围价格吗?

对于 WooCommerce 中的可变产品,您需要:

  • 定位可变产品类型
  • 获取最低价和最高价。

因此您应该需要获取产品对象的实例。一般来说,您可以通过以下方式获得它:

 global $product;

如果它不起作用你将使用 intead:

global $post;
$product = wc_get_product( $post->ID );

现在,您将使用以下内容:

<?php
global $product;

if ( isset( $ebookstore_theme_option['woo-list-price'] ) && $ebookstore_theme_option['woo-list-price'] == 'enable' ){

    // For all product types that are not "variable products"
    if( ! $product->is_type('variable') ){
        $ebookstore_woo .= '<strong class="amount">'.esc_attr($currency).''.$price_sale.'</strong>';
    }
    // For variable products    
    else {
        $min_price = $product->get_variation_price( 'min' );
        $max_price = $product->get_variation_price( 'max' );

        $ebookstore_woo .= '<strong class="amount">'.esc_attr($currency).''.$min_price.' - '.esc_attr($currency).''.$max_price.'</strong>';
    }
}

如您所见,我正在使用 WC_Product_Variable methods


可能你不知道,woocommerce 有几个格式化价格函数:

  • wc_price( $price );
  • wc_format_price_range( $from, $to );
  • wc_format_sale_price( $regular_price, $sale_price );

它们都会包括货币