Skip to content

Instantly share code, notes, and snippets.

@trey8611
Created August 27, 2025 14:22
Show Gist options
  • Save trey8611/25f84a5f4476128818a0dd84fed90116 to your computer and use it in GitHub Desktop.
Save trey8611/25f84a5f4476128818a0dd84fed90116 to your computer and use it in GitHub Desktop.
AnalyticsWP - Programmatically send reports with custom dates

AnalyticsWP Custom Date Range Email Reports

This enhancement adds the ability to programmatically send AnalyticsWP email reports with custom date ranges, allowing you to generate reports for any specific time period rather than just the predefined weekly and monthly schedules.

Features

  • Custom Date Ranges: Send reports for any specific date range (e.g., Q1 2024, last 90 days, specific campaign period)
  • Multiple Recipients: Send to custom email addresses or use the client site's configured recipients
  • Custom Subject Lines: Set custom subject lines for your reports
  • Error Handling: Comprehensive error handling and validation
  • WordPress Integration: Full integration with WordPress hooks and cron jobs

Requirements

  • AnalyticsWP plugin installed and activated
  • Agency Mode enabled (for multi-site functionality)
  • Client sites configured in Agency Mode
  • WordPress email functionality working properly

Basic Usage

Simple Custom Date Range Report

// Send a report for January 2024
$result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
    'https://example-client-site.com',
    '2024-01-01',
    '2024-01-31'
);

if (is_array($result) && $result['success']) {
    echo "Report sent successfully!";
} else {
    echo "Error: " . $result['error'];
}

Custom Email and Subject

$result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
    'https://example-client-site.com',
    '2024-01-01',
    '2024-01-31',
    '[email protected]',           // Custom email address
    'Q1 2024 Analytics Report'      // Custom subject line
);

Method Parameters

send_custom_date_range_report(
    string $client_site_url,        // Required: The client site URL
    string $start_date,             // Required: Start date (YYYY-MM-DD format)
    string $end_date,               // Required: End date (YYYY-MM-DD format)
    string $email_address = null,   // Optional: Custom email address
    string $subject_line = null     // Optional: Custom subject line
)

Return Values

The method returns an array with the following structure:

// Success
[
    'success' => true,
    'message' => 'Report sent successfully'
]

// Error
[
    'success' => false,
    'error' => 'Error description'
]

Common Use Cases

1. Quarterly Reports

function send_quarterly_report($client_site_url, $year, $quarter) {
    $quarters = [
        1 => ['start' => "{$year}-01-01", 'end' => "{$year}-03-31"],
        2 => ['start' => "{$year}-04-01", 'end' => "{$year}-06-30"],
        3 => ['start' => "{$year}-07-01", 'end' => "{$year}-09-30"],
        4 => ['start' => "{$year}-10-01", 'end' => "{$year}-12-31"],
    ];
    
    $range = $quarters[$quarter];
    
    return \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
        $client_site_url,
        $range['start'],
        $range['end'],
        null,
        "Q{$quarter} {$year} Analytics Report"
    );
}

// Usage
send_quarterly_report('https://example.com', 2024, 1);

2. Campaign Period Reports

function send_campaign_report($client_site_url, $campaign_name, $start_date, $end_date) {
    return \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
        $client_site_url,
        $start_date,
        $end_date,
        null,
        "{$campaign_name} Campaign Analytics Report"
    );
}

// Usage
send_campaign_report(
    'https://example.com',
    'Black Friday 2024',
    '2024-11-20',
    '2024-12-02'
);

3. Rolling Period Reports

function send_rolling_period_report($client_site_url, $days) {
    $end_date = date('Y-m-d');
    $start_date = date('Y-m-d', strtotime("-{$days} days"));
    
    return \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
        $client_site_url,
        $start_date,
        $end_date,
        null,
        "Last {$days} Days Analytics Report"
    );
}

// Usage
send_rolling_period_report('https://example.com', 30);  // Last 30 days
send_rolling_period_report('https://example.com', 90);  // Last 90 days

WordPress Integration

Hook into WordPress Events

// Send a report when a specific action occurs
add_action('my_custom_event', function($client_site_url) {
    $result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
        $client_site_url,
        date('Y-m-d', strtotime('-7 days')),
        date('Y-m-d'),
        null,
        'Weekly Summary Report'
    );
    
    if (is_array($result)) {
        error_log('Custom report result: ' . ($result['success'] ? 'Success' : $result['error']));
    }
});

Scheduled Reports with WP Cron

// Schedule a custom report to run monthly
function schedule_custom_monthly_reports() {
    if (!wp_next_scheduled('analyticswp_custom_monthly_reports')) {
        wp_schedule_event(strtotime('first day of next month 09:00'), 'monthly', 'analyticswp_custom_monthly_reports');
    }
}

add_action('analyticswp_custom_monthly_reports', function() {
    $client_sites = \AnalyticsWP\Lib\AgencyMode::get_client_sites();
    
    foreach ($client_sites as $client_site) {
        if ($client_site['monthlyReportsEnabled']) {
            $last_month_start = date('Y-m-01', strtotime('first day of last month'));
            $last_month_end = date('Y-m-t', strtotime('last day of last month'));
            
            \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
                $client_site['siteUrl'],
                $last_month_start,
                $last_month_end,
                null,
                'Monthly Analytics Report - ' . date('F Y', strtotime($last_month_start))
            );
        }
    }
});

// Activate the schedule
add_action('init', 'schedule_custom_monthly_reports');

Error Handling

The method includes comprehensive error handling for common issues:

  • Invalid client site URL: Returns error if client site not found
  • Invalid date format: Validates YYYY-MM-DD format
  • Invalid date range: Ensures end date is after start date
  • Missing recipients: Checks if email recipients are configured
  • API failures: Handles network and API errors gracefully

Best Practices

  1. Date Format: Always use YYYY-MM-DD format for dates
  2. Error Checking: Always check the return value for errors
  3. Logging: Log results for debugging and monitoring
  4. Rate Limiting: Don't send too many reports too quickly
  5. Testing: Test with small date ranges first

Troubleshooting

Common Issues

  1. "Client site not found"

    • Ensure the client site URL is exactly as configured in Agency Mode
    • Check that Agency Mode is enabled
  2. "Invalid date format"

    • Use YYYY-MM-DD format (e.g., '2024-01-31')
    • Don't use MM/DD/YYYY or other formats
  3. "No email recipients configured"

    • Configure email recipients in the client site settings
    • Or provide a custom email address parameter
  4. "Failed to send email"

    • Check WordPress email configuration
    • Verify SMTP settings if using an email plugin
    • Check server logs for email errors

Debug Mode

Enable WordPress debug mode to see detailed error messages:

// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

Security Considerations

  • The method uses the same authentication system as the existing email reports
  • Custom email addresses are validated
  • Date inputs are validated to prevent injection attacks
  • All API calls use proper authentication tokens

Performance Notes

  • Reports are generated in real-time from the client site's data
  • Large date ranges may take longer to process
  • Consider caching for frequently requested date ranges
  • Monitor server resources when sending multiple reports

Support

For issues or questions about this functionality:

  1. Check the error messages returned by the method
  2. Review WordPress error logs
  3. Verify client site configuration in Agency Mode
  4. Test with the example code provided

Changelog

  • v1.0: Initial implementation of custom date range reports
  • Added send_custom_date_range_report() method
  • Added support for custom email addresses and subject lines
  • Added comprehensive error handling and validation

More Examples

/**
 * Example: How to programmatically send AnalyticsWP email reports with custom date ranges
 * 
 * This file demonstrates how to use the new send_custom_date_range_report() method
 * to send email reports for specific date ranges.
 */

// Make sure we're in WordPress context
if (!defined('ABSPATH')) {
    require_once('../../../wp-load.php');
}

// Example 1: Send a custom date range report to a specific client site
function send_custom_report_example() {
    // Check if AgencyMode is available
    if (!class_exists('\AnalyticsWP\Lib\AgencyMode')) {
        echo "Error: AnalyticsWP AgencyMode not available\n";
        return;
    }

    // Example parameters
    $client_site_url = 'https://example-client-site.com'; // Replace with actual client site URL
    $start_date = '2024-01-01';
    $end_date = '2024-01-31';
    $custom_email = '[email protected]'; // Optional: override default recipients
    $custom_subject = 'Q1 2024 Analytics Report'; // Optional: custom subject line

    // Send the custom date range report
    $result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
        $client_site_url,
        $start_date,
        $end_date,
        $custom_email,
        $custom_subject
    );

    // Handle the result
    if (is_array($result)) {
        if ($result['success']) {
            echo "Success: " . $result['message'] . "\n";
        } else {
            echo "Error: " . $result['error'] . "\n";
        }
    } else {
        echo "Unexpected result format\n";
    }
}

// Example 2: Send reports for multiple date ranges
function send_multiple_custom_reports() {
    $client_site_url = 'https://example-client-site.com';
    
    // Define multiple date ranges
    $date_ranges = [
        ['start' => '2024-01-01', 'end' => '2024-01-31', 'name' => 'January 2024'],
        ['start' => '2024-02-01', 'end' => '2024-02-29', 'name' => 'February 2024'],
        ['start' => '2024-03-01', 'end' => '2024-03-31', 'name' => 'March 2024'],
    ];

    foreach ($date_ranges as $range) {
        $result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
            $client_site_url,
            $range['start'],
            $range['end'],
            null, // Use default recipients
            $range['name'] . ' Analytics Report'
        );

        if (is_array($result) && $result['success']) {
            echo "Sent report for " . $range['name'] . "\n";
        } else {
            echo "Failed to send report for " . $range['name'] . "\n";
        }
    }
}

// Example 3: Send a report for the last 90 days
function send_last_90_days_report() {
    $client_site_url = 'https://example-client-site.com';
    
    // Calculate dates for last 90 days
    $end_date = date('Y-m-d'); // Today
    $start_date = date('Y-m-d', strtotime('-89 days')); // 90 days ago (inclusive)

    $result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
        $client_site_url,
        $start_date,
        $end_date,
        null,
        'Last 90 Days Analytics Report'
    );

    if (is_array($result) && $result['success']) {
        echo "Sent 90-day report successfully\n";
    } else {
        echo "Failed to send 90-day report\n";
    }
}

// Example 4: WordPress hook to send custom reports on specific events
function send_custom_report_on_event() {
    // This could be hooked to various WordPress events
    add_action('analyticswp_send_custom_report', function($client_site_url, $start_date, $end_date) {
        $result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
            $client_site_url,
            $start_date,
            $end_date
        );
        
        // Log the result
        if (is_array($result)) {
            error_log('AnalyticsWP Custom Report: ' . ($result['success'] ? 'Success' : 'Error: ' . $result['error']));
        }
    }, 10, 3);
}

// Example 5: Cron job to send monthly reports on the 1st of each month
function schedule_monthly_custom_reports() {
    if (!wp_next_scheduled('analyticswp_monthly_custom_reports')) {
        wp_schedule_event(strtotime('first day of next month 09:00'), 'monthly', 'analyticswp_monthly_custom_reports');
    }
}

add_action('analyticswp_monthly_custom_reports', function() {
    // Get all client sites
    $client_sites = \AnalyticsWP\Lib\AgencyMode::get_client_sites();
    
    // Calculate last month's date range
    $last_month_start = date('Y-m-01', strtotime('first day of last month'));
    $last_month_end = date('Y-m-t', strtotime('last day of last month'));
    
    foreach ($client_sites as $client_site) {
        if ($client_site['monthlyReportsEnabled']) {
            $result = \AnalyticsWP\Lib\AgencyMode::send_custom_date_range_report(
                $client_site['siteUrl'],
                $last_month_start,
                $last_month_end,
                null,
                'Monthly Analytics Report - ' . date('F Y', strtotime($last_month_start))
            );
        }
    }
});

// Usage examples (uncomment to run):
// send_custom_report_example();
// send_multiple_custom_reports();
// send_last_90_days_report();
// schedule_monthly_custom_reports();

echo "Custom report examples loaded. Uncomment the function calls at the bottom to run them.\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment