Bit of a newbie... I have a survey and on submission, I am generating a dynamic coupon code to incentivize purchase of a product. When user adds a product to the cart, the discount code is applied successfully, however I would like to display a notice on the product page indicating that (because the user took the survey), they will receive a discount applied at checkout.
Code for adding the product to cart:
// Add generated coupon to cart add_action( 'woocommerce_add_to_cart', 'apply_matched_coupons' ); function apply_matched_coupons() { if ( is_cart() || is_checkout() ) return; // Load coupon code $coupon_code = WC()->session->get( 'unique_coupon' ); if ( $coupon_code && ! WC()->cart->has_discount( $coupon_code ) ) { WC()->cart->apply_coupon( $coupon_code ); // Apply coupon code WC()->session->__unset( 'unique_coupon' ); // remove session variable } }
One of the many ways I've tried to add a notice:
add_action( 'woocommerce_before_single_product', 'custom_message_before_single_product', 5 ); // For single product page function custom_message_before_single_product() { if ( $coupon_code && ! WC()->cart->has_discount( $coupon_code ) ) wc_print_notice(sprintf('You will receive a discount at checkout!', $coupon_code), 'notice'); }
I also tried product-based, but the notice appears regardless of whether a coupon has been created:
add_action( 'woocommerce_before_single_product', 'custom_message_before_single_product', 5 ); // For single product page function custom_message_before_single_product() { global $product; if ( $product->get_id() == 1218 && $coupon_code = WC()->session->get( 'unique_coupon' );) { wc_print_notice(sprintf('You will receive a discount at checkout!', $coupon_code), 'notice'); } }
Of course I'm basing this off the belief that because a session-based coupon was created, it's possible to grab that coupon, or recognize it has been created and display a notice prior to it being added to the cart but perhaps it's not possible...?
https://stackoverflow.com/questions/65895749/woocommerce-how-do-i-show-a-notice-on-product-page-if-a-wc-session-coupon-exist January 26, 2021 at 12:05PM
没有评论:
发表评论