PHP数值存为字符串?WooCommerce价格计算报错求助
Hey there, let's break down why you're hitting that Unsupported operand types error and how to fix it quickly.
What's Causing the Error?
The error points directly to your $minus = ($discount / 100) * $get_price; line, which means $get_price isn't a valid numeric type when you try to do math with it. This usually happens for a few common reasons:
- The
_regular_pricepost meta is empty (maybe the product doesn't have a regular price set) get_post_meta()returns a non-numeric value like an empty string ornull- You're working with a variable product where the regular price is stored differently than simple products
Step 1: Debug the $get_price Value
First, let's confirm exactly what you're pulling from get_post_meta(). Add these quick debug lines right after you fetch the price (make sure to remove them before going live):
$get_price = get_post_meta( $item_id, '_regular_price', true); // Debug output to check value and data type var_dump($get_price); echo '<br>Data Type: ' . gettype($get_price);
This will show you if you're getting an empty string, null, or something else instead of a proper number.
Step 2: Validate and Convert the Price to a Numeric Type
Once you know the issue, fix it by ensuring $get_price is a valid numeric value before doing calculations. Here's a robust way to handle it:
$get_price = get_post_meta( $item_id, '_regular_price', true); // Convert to float, default to 0 if value is empty or non-numeric $get_price = is_numeric($get_price) ? (float) $get_price : 0; $discount = 10; $minus = ($discount / 100) * $get_price; $price = wc_price($get_price - $minus);
This checks if the value is numeric first, then converts it to a float. If it's invalid, it defaults to 0 to avoid math errors entirely.
Step 3: Use WooCommerce's Official Price Methods (More Reliable)
Instead of directly reading post meta, use WooCommerce's built-in product methods. This handles edge cases like variable products, grouped products, or products with special pricing rules automatically:
// Get the official WC_Product object $product = wc_get_product($item_id); if ($product) { // Fetch regular price via WooCommerce's native method $regular_price = (float) $product->get_regular_price(); $discount = 10; $discounted_price = $regular_price - ($regular_price * $discount / 100); $price = wc_price($discounted_price); } else { // Handle case where the product doesn't exist $price = wc_price(0); }
This is the recommended approach because it leverages WooCommerce's internal logic to fetch the correct price, eliminating the risk of pulling invalid meta values.
Quick Recap
The core issue was invalid data coming from get_post_meta(). By validating/converting the price or using WooCommerce's official product methods, you'll wipe out that operand type error for good.
内容的提问来源于stack exchange,提问作者danyo

