如何修改WordPress插件以避免显示$0.00金额?
Hey there! I see you're trying to replace that pesky $0.00 price with a dash (-) in your food menu plugin, but your current code isn't working as expected. Let's break down the issue and fix it.
The Problem with Your Current Code
The root issue here is operator precedence in PHP. The string concatenation operator (.) has higher priority than the ternary operator (?:), so your code is actually executing in this order:
- First, it concatenates
'<span class="price">'with$gTotal - Then it compares that entire string to
'0.00'(which will almost always be false) - Finally, it runs the ternary logic based on that false result, leading to unexpected output
The Fixed Code
Wrap the ternary operation in parentheses to ensure it runs before the string concatenation. Here's the corrected version:
$gTotal = $foodmenu->getPriceWithLabel(); // Parentheses ensure we check $gTotal's value first $html .= '<span class="price">' . ($gTotal === '0.00' ? '-' : $gTotal) . '</span>'; $html .= "</div>";
A More Robust Alternative (Just in Case)
Wait a second—does getPriceWithLabel() return the price with a currency symbol, like $0.00 instead of just 0.00? If that's the case, your strict comparison (=== '0.00') won't match. For a more reliable solution that works regardless of currency formatting, extract the numeric value first:
$gTotal = $foodmenu->getPriceWithLabel(); // Strip non-numeric characters (like $ signs) and convert to a float $priceNumber = floatval(preg_replace('/[^0-9.]/', '', $gTotal)); // Use the dash if the price is 0, otherwise keep the original formatted price $displayPrice = $priceNumber === 0 ? '-' : $gTotal; $html .= '<span class="price">' . $displayPrice . '</span>'; $html .= "</div>";
This version handles cases where the price might have dollar signs, commas, or other formatting characters.
Quick Debug Tip
To make sure you're comparing the right value, add a quick debug line before your logic to see exactly what getPriceWithLabel() returns:
var_dump($gTotal); // This will show you the exact string/value you're working with
Just remember to remove that line once you're done debugging!
内容的提问来源于stack exchange,提问作者Nopistons

