daily pastebin goal
9%
SHARE
TWEET

Untitled

a guest Nov 23rd, 2017 47 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. /*
  4.  * Tell Gravity Forms about your custom merge tag: {edd_discount_code}
  5.  */
  6. function my_gf_add_merge_tags( $form ) {
  7.   ?>
  8.   <script type="text/javascript">
  9.     gform.addFilter('gform_merge_tags', 'searchwp_gf_add_merge_tags');
  10.     function searchwp_gf_add_merge_tags(mergeTags, elementId, hideAllFields, excludeFieldTypes, isPrepop, option){
  11.       mergeTags["custom"].tags.push({ tag: '{edd_discount_code}', label: 'EDD Discout Code' });
  12.  
  13.       return mergeTags;
  14.     }
  15.   </script>
  16.   <?php
  17.   return $form;
  18. }
  19.  
  20. add_action( 'gform_admin_pre_render', 'my_gf_add_merge_tags' );
  21.  
  22.  
  23. /*
  24.  * Handle your custom merge tag, swaps out merge tag placeholder with unique EDD Discount Code
  25.  */
  26. function my_gf_replace_download_link( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
  27.  
  28.   $custom_merge_tag = '{edd_discount_code}';
  29.  
  30.   if ( strpos( $text, $custom_merge_tag ) === false ) {
  31.     return $text;
  32.   }
  33.  
  34.   $new_code = my_edd_generate_discount_code();
  35.  
  36.   // Generate the actual EDD Discount Code
  37.   $discount_args = array(
  38.     'name'     => 'My Discount Code Name',
  39.     'code'     => $new_code,
  40.     'status'   => 'active',
  41.     'use_once' => true,
  42.     'max'      => '1',
  43.     'amount'   => 30,
  44.     'type'     => 'percent'
  45.   );
  46.  
  47.   $code_id = edd_store_discount( $discount_args );
  48.  
  49.   // Replace the merge tag with the discount code itself
  50.   $text = str_replace( $custom_merge_tag, $new_code, $text );
  51.  
  52.   return $text;
  53.  
  54. }
  55.  
  56. add_filter( 'gform_replace_merge_tags', 'my_gf_replace_download_link', 10, 7 );
  57.  
  58. // Generates a unique discount code
  59. function my_edd_generate_discount_code() {
  60.   do {
  61.     $salt = md5( time() . mt_rand() );
  62.     $code = substr( $salt, 0, 15 );
  63.   }
  64.  
  65.   while ( my_edd_discount_code_exists( $code ) );
  66.  
  67.   return $code;
  68.  
  69. }
  70.  
  71. // Checks whether a discount code exists
  72. function my_edd_discount_code_exists( $code ) {
  73.  
  74.   global $wpdb;
  75.  
  76.   $wpdb->get_results( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta where meta_key='_edd_discount_code' and meta_value=%s", $code ) );
  77.  
  78.   if ( ( $wpdb->num_rows ) > 0 ) {
  79.     return true;
  80.   }
  81.  
  82.     return false;
  83.  
  84. }
RAW Paste Data
Top