edd_ajax_apply_discount

Validates the supplied discount sent via AJAX.

Description

edd_ajax_apply_discount(); 

Usage

  1. if ( !function_exists( 'edd_ajax_apply_discount' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'easy-digital-downloads/includes/ajax-functions.php'; 
  3.  
  4.  
  5. // NOTICE! Understand what this does before running. 
  6. $result = edd_ajax_apply_discount(); 
  7.  

Defined (1)

The function is defined in the following location(s).

/includes/ajax-functions.php  
  1. function edd_ajax_apply_discount() { 
  2. if ( isset( $_POST['code'] ) ) { 
  3.  
  4. $discount_code = sanitize_text_field( $_POST['code'] ); 
  5.  
  6. $return = array( 
  7. 'msg' => '',  
  8. 'code' => $discount_code 
  9. ); 
  10.  
  11. $user = ''; 
  12.  
  13. if ( is_user_logged_in() ) { 
  14. $user = get_current_user_id(); 
  15. } else { 
  16. parse_str( $_POST['form'], $form ); 
  17. if ( ! empty( $form['edd_email'] ) ) { 
  18. $user = urldecode( $form['edd_email'] ); 
  19.  
  20. if ( edd_is_discount_valid( $discount_code, $user ) ) { 
  21. $discount = edd_get_discount_by_code( $discount_code ); 
  22. $amount = edd_format_discount_rate( edd_get_discount_type( $discount->ID ), edd_get_discount_amount( $discount->ID ) ); 
  23. $discounts = edd_set_cart_discount( $discount_code ); 
  24. $total = edd_get_cart_total( $discounts ); 
  25.  
  26. $return = array( 
  27. 'msg' => 'valid',  
  28. 'amount' => $amount,  
  29. 'total_plain' => $total,  
  30. 'total' => html_entity_decode( edd_currency_filter( edd_format_amount( $total ) ), ENT_COMPAT, 'UTF-8' ),  
  31. 'code' => $discount_code,  
  32. 'html' => edd_get_cart_discounts_html( $discounts ) 
  33. ); 
  34. } else { 
  35. $errors = edd_get_errors(); 
  36. $return['msg'] = $errors['edd-discount-error']; 
  37. edd_unset_error( 'edd-discount-error' ); 
  38.  
  39. // Allow for custom discount code handling 
  40. $return = apply_filters( 'edd_ajax_discount_response', $return ); 
  41.  
  42. echo json_encode($return); 
  43. edd_die();