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.
- 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
- AnalyticsWP plugin installed and activated
- Agency Mode enabled (for multi-site functionality)
- Client sites configured in Agency Mode
- WordPress email functionality working properly
// 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'];
}
$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
);
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
)
The method returns an array with the following structure:
// Success
[
'success' => true,
'message' => 'Report sent successfully'
]
// Error
[
'success' => false,
'error' => 'Error description'
]
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);
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'
);
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
// 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']));
}
});
// 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');
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
- Date Format: Always use YYYY-MM-DD format for dates
- Error Checking: Always check the return value for errors
- Logging: Log results for debugging and monitoring
- Rate Limiting: Don't send too many reports too quickly
- Testing: Test with small date ranges first
-
"Client site not found"
- Ensure the client site URL is exactly as configured in Agency Mode
- Check that Agency Mode is enabled
-
"Invalid date format"
- Use YYYY-MM-DD format (e.g., '2024-01-31')
- Don't use MM/DD/YYYY or other formats
-
"No email recipients configured"
- Configure email recipients in the client site settings
- Or provide a custom email address parameter
-
"Failed to send email"
- Check WordPress email configuration
- Verify SMTP settings if using an email plugin
- Check server logs for email errors
Enable WordPress debug mode to see detailed error messages:
// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
- 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
- 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
For issues or questions about this functionality:
- Check the error messages returned by the method
- Review WordPress error logs
- Verify client site configuration in Agency Mode
- Test with the example code provided
- 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
/**
* 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";