You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ACF自定义字段'custom_price'替换WooCommerce购物车商品价格

Replace Hardcoded Price with ACF Custom Field in WooCommerce

To use your ACF custom_price field instead of the hardcoded value, you'll need to fetch the field value dynamically for each product in the cart. Here's the updated, functional code:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart ) {
    // Prevent infinite loops in admin area
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    foreach ( $cart->cart_contents as $item ) {
        // Get the product object from the cart item
        $product = $item['data'];
        // Fetch the ACF custom price for this specific product
        $custom_price = get_field( 'custom_price', $product->get_id() );

        // Only apply the custom price if it's a valid positive number
        if ( is_numeric( $custom_price ) && $custom_price > 0 ) {
            $product->set_price( $custom_price );
            // Set regular price too for consistency (avoids display glitches)
            $product->set_regular_price( $custom_price );
        }
    }
}

Key Changes Explained:

  • Removed hardcoded value: Instead of a fixed 10, we pull the price directly from each product's ACF field
  • Dynamic per-product pricing: We loop through every cart item and fetch the custom_price value specific to that product using ACF's get_field() function
  • Validation check: We ensure the custom price is a valid number greater than 0 to prevent errors if the field is empty or set incorrectly
  • Consistent pricing: Setting both set_price() and set_regular_price() ensures the custom price shows up correctly in cart totals, checkout, and product pages
  • Admin loop protection: The is_admin() check stops the function from running unnecessarily in the WordPress backend, avoiding unexpected behavior

Important Notes:

  • Confirm your ACF field named custom_price is set to a Number field type and assigned to the WooCommerce Product post type
  • If a product doesn't have a value in the custom_price field, it will keep its original default price
  • Add this code to your child theme's functions.php file or a custom plugin (never edit core WooCommerce or parent theme files directly)

内容的提问来源于stack exchange,提问作者jord49

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:10:07