1

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...?

  • Your question is not clear as your code is not testable… Note that *"The question should be updated to include desired behavior, a specific problem or error, **and the shortest code necessary to reproduce the problem**."* – LoicTheAztec Jan 27 '21 at 06:18

0 Answers0