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

问题描述

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

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

解决方法

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

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',2 );

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...