如何用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_pricevalue specific to that product using ACF'sget_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()andset_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_priceis 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_pricefield, it will keep its original default price - Add this code to your child theme's
functions.phpfile or a custom plugin (never edit core WooCommerce or parent theme files directly)
内容的提问来源于stack exchange,提问作者jord49
相关产品推荐
相关产品推荐

