将可变产品价格范围替换为“来自:”+ WooCommerce 中的最低价格

问题描述 投票:0回答:1

在 WooCommerce 中,当可变产品具有不同价格的变体时,它会显示包含 2 个金额的价格范围:例如 89.00 - 109.00。

我想更改它,仅显示“来自:”和最低价格,例如

From: 89.00
(删除最高价格)。
(“Fra:”在我的语言中是“from”的意思,只是为了澄清)。

这是我尝试过的代码:

// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'Fra: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'Fra: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
$price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
}
return $price;
}

此代码不起作用。每当我添加它时,什么都不会发生。

我需要更改什么才能获取“发件人:”+最低价格?

php wordpress woocommerce string-formatting product-price
1个回答
13
投票

你的代码有点不完整,因为缺少钩子和函数......

以下是使其适用于您的可变产品的正确方法:

add_filter( 'woocommerce_get_price_html', 'change_variable_products_price_display', 10, 2 );
function change_variable_products_price_display( $price, $product ) {

    // Only for variable products type
    if( ! $product->is_type('variable') ) return $price;

    $prices = $product->get_variation_prices( true );

    if ( empty( $prices['price'] ) )
        return apply_filters( 'woocommerce_variable_empty_price_html', '', $product );

    $min_price = current( $prices['price'] );
    $max_price = end( $prices['price'] );
    $prefix_html = '<span class="price-prefix">' . __('Fra: ') . '</span>';

    $prefix = $min_price !== $max_price ? $prefix_html : ''; // HERE the prefix

    return apply_filters( 'woocommerce_variable_price_html', $prefix . wc_price( $min_price ) . $product->get_price_suffix(), $product );
}

代码位于活动子主题(或主题)的 function.php 文件中,或者也位于任何插件文件中。

已测试且有效。

© www.soinside.com 2019 - 2024. All rights reserved.