Spin Wheel

⌘K
  1. Home
  2. Spin Wheel
  3. Hooks & Filters (Deve...
  4. Before saving to database (uspw_before_save_entry)

Before saving to database (uspw_before_save_entry)

uspw_before_save_entry

Description

Fires before entry data is saved to the database, allowing developers to modify, enrich, or validate the data before storage.

Hook Type: Filter
Since: 1.0.0

Parameters

ParameterTypeDescription
$dataarrayEntry data
$campaign_idintThe ID of the spin wheel campaign

Usage

add_filter( 'uspw_before_save_entry', 'my_data_enrichment', 10, 2 );
function my_data_enrichment( $data, $campaign_id ) {
    // Your custom logic here
    // Modify $data as needed
    return $data;
}

Real-World Examples

Example 1: Add UTM Parameters for Attribution Tracking

Capture and store UTM parameters for marketing attribution.

add_action( 'uspw_before_save_entry', 'add_utm_tracking', 10, 2 );
function add_utm_tracking( &$data, $campaign_id ) {
    // Capture UTM parameters from URL
    $utm_params = [
        'utm_source' => sanitize_text_field( $_GET['utm_source'] ?? '' ),
        'utm_medium' => sanitize_text_field( $_GET['utm_medium'] ?? '' ),
        'utm_campaign' => sanitize_text_field( $_GET['utm_campaign'] ?? '' ),
        'utm_term' => sanitize_text_field( $_GET['utm_term'] ?? '' ),
        'utm_content' => sanitize_text_field( $_GET['utm_content'] ?? '' )
    ];
    
    // Add to data array
    $data['utm_source'] = $utm_params['utm_source'];
    $data['utm_medium'] = $utm_params['utm_medium'];
    $data['utm_campaign'] = $utm_params['utm_campaign'];
    
    // Store full UTM data in others_data JSON field
    if ( ! empty( $data['others_data'] ) ) {
        $others = json_decode( $data['others_data'], true );
    } else {
        $others = [];
    }
    
    $others['utm_tracking'] = array_filter( $utm_params ); // Remove empty values
    $others['referrer'] = $_SERVER['HTTP_REFERER'] ?? '';
    $others['landing_page'] = $_SERVER['REQUEST_URI'] ?? '';
    
    $data['others_data'] = wp_json_encode( $others );
}

Example 2: Enrich Data with Geolocation

Add geographic information based on the user’s IP address.

add_action( 'uspw_before_save_entry', 'add_geolocation_data', 10, 2 );
function add_geolocation_data( &$data, $campaign_id ) {
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    
    // Use a geolocation API (example: ipapi.co)
    $response = wp_remote_get( "https://ipapi.co/{$ip_address}/json/" );
    
    if ( ! is_wp_error( $response ) ) {
        $geo_data = json_decode( wp_remote_retrieve_body( $response ), true );
        
        if ( ! empty( $geo_data ) ) {
            // Add geo data to entry
            $data['country'] = $geo_data['country_name'] ?? '';
            $data['country_code'] = $geo_data['country_code'] ?? '';
            $data['city'] = $geo_data['city'] ?? '';
            $data['region'] = $geo_data['region'] ?? '';
            $data['timezone'] = $geo_data['timezone'] ?? '';
            
            // Store detailed geo data in JSON field
            if ( ! empty( $data['others_data'] ) ) {
                $others = json_decode( $data['others_data'], true );
            } else {
                $others = [];
            }
            
            $others['geolocation'] = [
                'ip' => $ip_address,
                'latitude' => $geo_data['latitude'] ?? '',
                'longitude' => $geo_data['longitude'] ?? '',
                'postal' => $geo_data['postal'] ?? '',
                'org' => $geo_data['org'] ?? ''
            ];
            
            $data['others_data'] = wp_json_encode( $others );
        }
    }
}

Example 3: Normalize and Validate Phone Numbers

Standardize phone number formats before saving.

add_action( 'uspw_before_save_entry', 'normalize_phone_number', 10, 2 );
function normalize_phone_number( &$data, $campaign_id ) {
    if ( empty( $data['phone'] ) ) {
        return;
    }
    
    // Remove all non-numeric characters
    $phone = preg_replace( '/[^0-9]/', '', $data['phone'] );
    
    // Format based on length
    if ( strlen( $phone ) === 10 ) {
        // US format: (555) 123-4567
        $data['phone'] = sprintf(
            '(%s) %s-%s',
            substr( $phone, 0, 3 ),
            substr( $phone, 3, 3 ),
            substr( $phone, 6 )
        );
        $data['phone_country'] = 'US';
    } elseif ( strlen( $phone ) === 11 && substr( $phone, 0, 1 ) === '1' ) {
        // US with country code
        $data['phone'] = sprintf(
            '+1 (%s) %s-%s',
            substr( $phone, 1, 3 ),
            substr( $phone, 4, 3 ),
            substr( $phone, 7 )
        );
        $data['phone_country'] = 'US';
    } else {
        // International - store as-is with + prefix
        $data['phone'] = '+' . $phone;
        $data['phone_country'] = 'International';
    }
    
    // Store raw phone for easier searching
    $data['phone_raw'] = $phone;
}

Example 4: Add Custom Scoring for Lead Quality

Calculate and store a lead quality score based on various factors.

add_action( 'uspw_before_save_entry', 'calculate_lead_score', 10, 2 );
function calculate_lead_score( &$data, $campaign_id ) {
    $score = 0;
    
    // Email domain scoring
    if ( ! empty( $data['email'] ) ) {
        $email_domain = substr( strrchr( $data['email'], '@' ), 1 );
        
        // Business emails score higher
        $business_domains = [ 'company.com', 'business.org', 'enterprise.net' ];
        if ( in_array( $email_domain, $business_domains, true ) ) {
            $score += 30;
        }
        
        // Free email providers score lower
        $free_domains = [ 'gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com' ];
        if ( in_array( $email_domain, $free_domains, true ) ) {
            $score += 10;
        } else {
            $score += 20; // Custom domain
        }
    }
    
    // Phone number provided
    if ( ! empty( $data['phone'] ) ) {
        $score += 15;
    }
    
    // Company name provided
    if ( ! empty( $data['company'] ) ) {
        $score += 25;
    }
    
    // UTM source scoring
    if ( ! empty( $data['utm_source'] ) ) {
        $high_value_sources = [ 'google-ads', 'linkedin', 'partner-referral' ];
        if ( in_array( $data['utm_source'], $high_value_sources, true ) ) {
            $score += 20;
        }
    }
    
    // Prize value (higher value prizes = more engaged users)
    $prize_value = floatval( $data['prize_value'] ?? 0 );
    if ( $prize_value >= 50 ) {
        $score += 10;
    }
    
    // Store the score
    $data['lead_score'] = min( $score, 100 ); // Cap at 100
    
    // Add lead grade
    if ( $score >= 80 ) {
        $data['lead_grade'] = 'A';
    } elseif ( $score >= 60 ) {
        $data['lead_grade'] = 'B';
    } elseif ( $score >= 40 ) {
        $data['lead_grade'] = 'C';
    } else {
        $data['lead_grade'] = 'D';
    }
}

Example 5: Integrate with Email Verification Service

Verify email addresses in real-time before saving.

add_action( 'uspw_before_save_entry', 'verify_email_address', 10, 2 );
function verify_email_address( &$data, $campaign_id ) {
    if ( empty( $data['email'] ) ) {
        return;
    }
    
    // Use an email verification API (example: ZeroBounce, Hunter.io)
    $api_key = get_option( 'zerobounce_api_key' );
    
    if ( $api_key ) {
        $endpoint = 'https://api.zerobounce.net/v2/validate';
        $response = wp_remote_get( add_query_arg( [
            'api_key' => $api_key,
            'email' => $data['email'],
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? ''
        ], $endpoint ) );
        
        if ( ! is_wp_error( $response ) ) {
            $result = json_decode( wp_remote_retrieve_body( $response ), true );
            
            // Store verification results
            $data['email_status'] = $result['status'] ?? 'unknown';
            $data['email_sub_status'] = $result['sub_status'] ?? '';
            $data['email_free_email'] = $result['free_email'] ?? false;
            $data['email_did_you_mean'] = $result['did_you_mean'] ?? '';
            
            // Add to others_data for detailed tracking
            if ( ! empty( $data['others_data'] ) ) {
                $others = json_decode( $data['others_data'], true );
            } else {
                $others = [];
            }
            
            $others['email_verification'] = [
                'status' => $result['status'] ?? '',
                'sub_status' => $result['sub_status'] ?? '',
                'account' => $result['account'] ?? '',
                'domain' => $result['domain'] ?? '',
                'mx_found' => $result['mx_found'] ?? '',
                'smtp_provider' => $result['smtp_provider'] ?? '',
                'verified_at' => current_time( 'mysql' )
            ];
            
            $data['others_data'] = wp_json_encode( $others );
            
            // Optionally block invalid emails
            if ( in_array( $result['status'], [ 'invalid', 'catch-all', 'spamtrap' ], true ) ) {
                $data['email_valid'] = false;
                // You could also prevent saving by calling wp_send_json_error here
            } else {
                $data['email_valid'] = true;
            }
        }
    }
}

Notes

  • The $data parameter is passed by reference (&$data), so modifications will be saved to the database.
  • This hook fires after default data is merged but before the database insert.
  • Perfect for data enrichment, normalization, validation, and adding custom fields.
  • Be cautious with external API calls as they can slow down the spin process – consider using async processing for non-critical enrichment.

How can we help?