如何让Woocommerce批发用户角色显示自定义字段商品价格?
实现批发用户自定义价格显示
问题描述
我已创建名为“Wholesale(批发)”的用户角色,通过以下代码为每个商品添加了可输入值的自定义字段snippet_wholesale,该字段可正常保存数据。现希望登录的批发用户看到该自定义字段设置的价格,而非商品常规价格。尝试过相关方案但无效,请问如何实现?
用户已实现的自定义字段代码:
function snippet_add_custom_pricing() { $args = array( 'label' => __( 'Wholesale', 'woocommerce' ), 'placeholder' => __( 'Price for wholesale', 'woocommerce' ), 'id' => 'snippet_wholesale', 'desc_tip' => true, 'description' => __( 'Price for Wholesale.', 'woocommerce' ), ); woocommerce_wp_text_input( $args ); } add_action( 'woocommerce_product_options_pricing', 'snippet_add_custom_pricing' ); function snippet_save_custom_meta( $post_id ) { // 获取价格值 $pricing = isset( $_POST[ 'snippet_wholesale' ] ) ? sanitize_text_field( $_POST[ 'snippet_wholesale' ] ) : ''; // 获取商品对象 $product = wc_get_product( $post_id ); // 保存自定义字段 $product->update_meta_data( 'snippet_wholesale', $pricing ); $product->save(); } add_action( 'woocommerce_process_product_meta', 'snippet_save_custom_meta' );
解决方案
添加以下代码到主题的functions.php文件或自定义插件中,即可实现批发用户看到自定义价格:
// 替换商品显示价格为批发价格(针对批发用户) function set_wholesale_price_for_wholesale_users( $price, $product ) { // 检查用户是否登录且属于批发角色 if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); // 注意:此处角色slug需与你创建的批发角色slug一致,默认用'wholesale' if ( in_array( 'wholesale', $current_user->roles ) ) { // 获取自定义批发价格 $wholesale_price = $product->get_meta( 'snippet_wholesale' ); // 仅当批发价格有效时替换 if ( ! empty( $wholesale_price ) && is_numeric( $wholesale_price ) ) { $price = $wholesale_price; } } } return $price; } add_filter( 'woocommerce_product_get_price', 'set_wholesale_price_for_wholesale_users', 10, 2 ); add_filter( 'woocommerce_product_variation_get_price', 'set_wholesale_price_for_wholesale_users', 10, 2 ); // 确保购物车和结算页同步使用批发价格 function apply_wholesale_price_to_cart( $cart_object ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { return; } if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); if ( in_array( 'wholesale', $current_user->roles ) ) { foreach ( $cart_object->get_cart() as $cart_item ) { $wholesale_price = $cart_item['data']->get_meta( 'snippet_wholesale' ); if ( ! empty( $wholesale_price ) && is_numeric( $wholesale_price ) ) { $cart_item['data']->set_price( $wholesale_price ); } } } } } add_action( 'woocommerce_before_calculate_totals', 'apply_wholesale_price_to_cart', 10, 1 );
代码说明
- 前端价格替换:通过
woocommerce_product_get_price和woocommerce_product_variation_get_price两个核心钩子,拦截商品价格输出逻辑,判断用户角色后替换为批发价格。 - 购物车价格同步:使用
woocommerce_before_calculate_totals钩子,确保购物车、结算页的价格也同步替换为批发价格,避免前后端价格不一致。 - 兼容性处理:加入对管理员后台和AJAX场景的判断,避免后台操作受影响;同时仅当批发价格为有效数值时才替换,否则 fallback 到商品常规价格。
内容的提问来源于stack exchange,提问作者Sophie
相关产品推荐
相关产品推荐

