Woocommerce中特定产品的动态销售价格显示

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

我需要在函数文件中开发一个脚本,显示注册用户的特定类别的销售价格。这段代码很好用。

我需要为它添加销售价格设计

function thenga_customer_specific_pricing( $price, $product ) {    
    if ( ! is_user_logged_in() ) {
        return $price;
    }

    $id = $product->get_id();

    if( has_term( 'daniel-wellington', 'product_cat' ,$id ) ){
        // Give these customers a 20% discount.
        return $price * 0.8;
    } elseif( has_term( 'giardino-segreto', 'product_cat' ,$id ) ){
        return $price * 0.85;
    } else {
        return $price;
    }
}
add_filter( 'woocommerce_product_get_price', 'thenga_customer_specific_pricing', 10, 2 );

我期待这样的输出:

是:100€现在:80€

我试过这个过滤器:

function custom_dynamic_sale_price_html( $price_html, $product ) {
    if( $product->is_type('variable') ) return $price_html;

    $price_html = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ), wc_get_price_to_display(  $product, array( 'price' => $product->get_sale_price() ) ) ) . $product->get_price_suffix();

    return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'custom_dynamic_sale_price_html', 20, 2 );

但它适用于所有产品,我如何只在特定类别中调用此过滤器?

php wordpress woocommerce price discount
1个回答
2
投票

以下代码将显示您的预期输出(对于简单产品):

// Discount prices
add_filter( 'woocommerce_product_get_price', 'specific_discounted_product_prices', 10, 2 );
function specific_discounted_product_prices( $price, $product ) {
    // For logged in customers
    if ( is_user_logged_in() ) {
        if( has_term( 'daniel-wellington', 'product_cat' ,$product->get_id() ) ){
            $price *= 0.8; // 20% discount
        } elseif( has_term( 'giardino-segreto', 'product_cat' ,$product->get_id() ) ){
            $price *= 0.85; // 15% discount
        }
    }
    return $price;
}

// Display the discount
add_filter( 'woocommerce_get_price_html', 'specific_discounted_product_prices_display', 10, 2 );
function specific_discounted_product_prices_display( $price, $product ) {
    // For simple products and logged in customers
    if( $product->is_type('simple') && is_user_logged_in() ){
        $regular_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
        $sale_price    = wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) );
        $active_price  = wc_get_price_to_display( $product );

        if( $regular_price != $active_price ) {
            if( $product->is_on_sale() )
                $price = sprintf( 'Was: %s – Now: %s', wc_price($sale_price), wc_price($active_price) );
            else
                $price = sprintf( 'Was: %s – Now: %s', wc_price($regular_price), wc_price($active_price) );
        }
    }
    return $price;
}

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

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