WooCommerce结合JQuery与PHP实现小计超500且用户为好友时元素淡入
Revised Code to Meet Your Requirement
Got it, let's fix this code to make sure the target element fades in only when both the WooCommerce cart subtotal is over 500 AND the user type is set to "friend". Here's the complete, polished version:
function customer_type_js() { // Ensure WooCommerce is available before accessing the cart if ( ! function_exists( 'WC' ) ) return; $wc_cart = WC()->cart; // Get the raw numeric subtotal (no currency symbols or formatting) $subtotal = $wc_cart->subtotal; echo "<script type='text/javascript'> jQuery(document).ready(function () { // Reusable function to validate conditions and update UI function validateCartAndUserType() { const customerType = jQuery('#customer_type').val(); const cartSubtotal = " . esc_js( $subtotal ) . "; // Check both required conditions together if (customerType === 'friend' && cartSubtotal > 500) { jQuery('#billing_field').fadeIn(); jQuery('.std-checkout-button').fadeOut(); } else { // Reset elements if conditions aren't met jQuery('#billing_field').fadeOut(); jQuery('.std-checkout-button').fadeIn(); } } // Run validation on page load (in case user type is already set to 'friend') validateCartAndUserType(); // Re-run validation whenever the user type changes jQuery('#customer_type').on('change', validateCartAndUserType); // Optional: Re-check if cart updates dynamically (e.g., via AJAX) jQuery(document.body).on('updated_cart_totals', validateCartAndUserType); }); </script>"; } // Hook the function to load in the footer (ensures jQuery is loaded) add_action( 'wp_footer', 'customer_type_js' );
Key Improvements & Explanations:
- Safe Cart Initialization: Used
WC()->cart(the official WooCommerce way) instead of an undefined$wc_cart, with a check to avoid errors if WooCommerce isn't active. - Dual Condition Check: Added the
cartSubtotal > 500check alongside the user type validation, using&&to ensure both conditions must be true for the elements to change. - Reusable Validation Function: Created
validateCartAndUserType()to avoid code duplication—this lets us run the check on page load and when the user type changes. - UI Reset Logic: Added an
elseblock to hide/show elements correctly if the user switches away from "friend" or the cart subtotal drops below 500. - Dynamic Cart Support: Included an optional listener for WooCommerce's
updated_cart_totalsevent, which re-runs the validation if the cart changes via AJAX (e.g., adding/removing items). - Security: Used
esc_js()to safely pass the PHP subtotal value to JavaScript, preventing potential XSS issues.
内容的提问来源于stack exchange,提问作者Erika Johansson
相关产品推荐
相关产品推荐

