edd_add_discount

Sets up and stores a new discount code.

Description

edd_add_discount( (array) $data ); 

Parameters (1)

0. $data (array)
Discount code data

Usage

  1. if ( !function_exists( 'edd_add_discount' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'easy-digital-downloads/includes/admin/discounts/discount-actions.php'; 
  3.  
  4. // Discount code data 
  5. $data = array(); 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = edd_add_discount($data); 
  9.  

Defined (1)

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

/includes/admin/discounts/discount-actions.php  
  1. function edd_add_discount( $data ) { 
  2.  
  3. if ( ! isset( $data['edd-discount-nonce'] ) || ! wp_verify_nonce( $data['edd-discount-nonce'], 'edd_discount_nonce' ) ) { 
  4. return; 
  5.  
  6. if( ! current_user_can( 'manage_shop_discounts' ) ) { 
  7. wp_die( __( 'You do not have permission to create discount codes', 'easy-digital-downloads' ), __( 'Error', 'easy-digital-downloads' ), array( 'response' => 403 ) ); 
  8.  
  9. // Setup the discount code details 
  10. $posted = array(); 
  11.  
  12. if ( empty( $data['name'] ) || empty( $data['code'] ) || empty( $data['type'] ) || empty( $data['amount'] ) ) { 
  13. wp_redirect( add_query_arg( 'edd-message', 'discount_validation_failed' ) ); 
  14. edd_die(); 
  15.  
  16. if ( ! ctype_alnum( $data['code'] ) ) { 
  17. wp_redirect( add_query_arg( 'edd-message', 'discount_invalid_code' ) ); 
  18. edd_die(); 
  19.  
  20. foreach ( $data as $key => $value ) { 
  21.  
  22. if ( $key === 'products' || $key === 'excluded-products' ) { 
  23.  
  24. foreach ( $value as $product_key => $product_value ) { 
  25. $value[ $product_key ] = preg_replace("/[^0-9_]/", '', $product_value ); 
  26.  
  27. $posted[ $key ] = $value; 
  28.  
  29. } else if ( $key != 'edd-discount-nonce' && $key != 'edd-action' && $key != 'edd-redirect' ) { 
  30.  
  31. if ( is_string( $value ) || is_int( $value ) ) { 
  32.  
  33. $posted[ $key ] = strip_tags( addslashes( $value ) ); 
  34.  
  35. } elseif ( is_array( $value ) ) { 
  36.  
  37. $posted[ $key ] = array_map( 'absint', $value ); 
  38.  
  39.  
  40.  
  41. // Ensure this discount doesn't already exist 
  42. if ( ! edd_get_discount_by_code( $posted['code'] ) ) { 
  43.  
  44. // Set the discount code's default status to active 
  45. $posted['status'] = 'active'; 
  46.  
  47. if ( edd_store_discount( $posted ) ) { 
  48.  
  49. wp_redirect( add_query_arg( 'edd-message', 'discount_added', $data['edd-redirect'] ) ); edd_die(); 
  50.  
  51. } else { 
  52.  
  53. wp_redirect( add_query_arg( 'edd-message', 'discount_add_failed', $data['edd-redirect'] ) ); edd_die(); 
  54.  
  55.  
  56. } else { 
  57.  
  58. wp_redirect( add_query_arg( 'edd-message', 'discount_exists', $data['edd-redirect'] ) ); edd_die(); 
  59.  
  60.