基于WooCommerce中产品的自定义产品价格后缀

时间:2020-08-11 12:39:02

标签: php wordpress woocommerce product suffix

我需要帮助才能显示每种产品的不同价格后缀。目前,我已经找到了可以按类别显示价格后缀的代码,但是它不能解决问题,因为我需要针对同一类别中的某些产品使用不同的价格。

Custom product price suffix for selected product categories in WooCommerce 答案代码基于类别。可以仅对特定产品进行更改吗?

1 个答案:

答案 0 :(得分:1)

以防万一有人想知道如何根据已经存在的代码来应用它。

in_array-检查数组中是否存在值

function filter_woocommerce_get_price_html( $price, $product ) {
    // Set specfic product ID's
    $specific_product_ids = array( 1, 2, 3 );

    // Checks if a value exists in an array
    if ( in_array( $product->get_id(), $specific_product_ids ) ) {
        $price .= ' ' . __( 'per kg', 'woocommerce' );
    }

    return $price;
}
add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 );

要处理多个后缀,可以使用PHP: switch

function filter_woocommerce_get_price_html( $price, $product ) {
    // Get product ID
    $product_id = $product->get_id();
    
    // Set product ID's kg
    $product_ids_kg = array( 30, 813, 815 );
    
    // Set product ID's g
    $product_ids_g = array( 817, 819, 821 );
    
    // Checks if a value exists in an array 
    switch ( $product_id ) {
        case in_array( $product_id, $product_ids_kg ):
            $suffix = ' per kg';
            break;
        case in_array( $product_id, $product_ids_g ):
            $suffix = ' per 500g';
            break;
        default:
            $suffix = '';
    }

    // Return
    return $price . __( $suffix, 'woocommerce' );
}
add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 );