Schedule API Call Script
November 28, 2024 · AI Conversations
// URL for Google Places API
$url = "https://maps.googleapis.com/maps/api/place/details/json?place_id={$placeId}&key={$apiKey}";
// Make the API request
$response = file_get_contents($url);
$data = json_decode($response, true);
// Check if the request was successful
if ($data['status'] === 'OK') {
// Extract rating and user reviews count
$rating = $data['result']['rating'] ?? null;
$userRatingsTotal = $data['result']['user_ratings_total'] ?? null;
return [
'rating' => $rating,
'user_ratings_total' => $userRatingsTotal,
];
} else {
// Handle error
return [
'error' => $data['status'],
];
}
}
// Example usage
$placeId = 'ChIJBSE5-GHlxUcR6q8o4ULyapo'; // Replace with your Google Place ID
$apiKey = 'AIzaSyAa_Iwek39wnF3uHaoZ3qB0QkFzTcVeYto'; // Replace with your API key
$placeDetails = getPlaceDetails($placeId, $apiKey);
if (isset($placeDetails['error'])) {
//echo "Error: " . $placeDetails['error'];
} else {
update_option('google_rating', $placeDetails['rating']);
update_option('google_rating_total', $placeDetails['user_ratings_total']);
}
set above code to run every 2 hours
### Option 1: Using Cron Jobs
If you're on a server with access to cron jobs, you can create a cron job that executes a PHP script every two hours.
1. **Create a PHP file** (e.g., `update_place_details.php`) and place your code in it:
<?php
function getPlaceDetails($placeId, $apiKey) {
// URL for Google Places API
$url = "https://maps.googleapis.com/maps/api/place/details/json?place_id={$placeId}&key={$apiKey}";
// Make the API request
$response = file_get_contents($url);
$data = json_decode($response, true);
// Check if the request was successful
if ($data['status'] === 'OK') {
// Extract rating and user reviews count
$rating = $data['result']['rating'] ?? null;
$userRatingsTotal = $data['result']['user_ratings_total'] ?? null;
return [
'rating' => $rating,
'user_ratings_total' => $userRatingsTotal,
];
} else {
// Handle error
return [
'error' => $data['status'],
];
}
}
// Example usage
$placeId = 'ChIJBSE5-GHlxUcR6q8o4ULyapo'; // Replace with your Google Place ID
$apiKey = 'YOUR_API_KEY'; // Replace with your API key
$placeDetails = getPlaceDetails($placeId, $apiKey);
if (isset($placeDetails['error'])) {
// Handle error (e.g., log it)
} else {
// Assuming update_option is a function that exists in your environment
update_option('google_rating', $placeDetails['rating']);
update_option('google_rating_total', $placeDetails['user_ratings_total']);
}
?>
2. **Set up a cron job**:
Open your terminal and type `crontab -e` to edit your cron jobs. Add the following line to run the script every two hours:
0 */2 * * * /usr/bin/php /path/to/update_place_details.php
Replace `/usr/bin/php` with the path to your PHP executable and `/path/to/update_place_details.php` with the full path to your script.
### Option 2: Using WordPress Cron
If you're using WordPress, you can utilize WordPress's built-in cron functionality:
1. **Add the following code to your theme's `functions.php` file** or a custom plugin:
// Schedule an event if it's not already scheduled
if (!wp_next_scheduled('update_google_place_details')) {
wp_schedule_event(time(), 'two_hours', 'update_google_place_details');
}
// Add the custom interval for two hours
add_filter('cron_schedules', function ($schedules) {
$schedules['two_hours'] = [
'interval' => 7200, // 2 hours in seconds
'display' => __('Every Two Hours')
];
return $schedules;
});
// Hook the function to your scheduled event
add_action('update_google_place_details', 'my_update_place_details');
function my_update_place_details() {
$placeId = 'ChIJBSE5-GHlxUcR6q8o4ULyapo'; // Replace with your Google Place ID
$apiKey = 'YOUR_API_KEY'; // Replace with your API key
$placeDetails = getPlaceDetails($placeId, $apiKey);
if (isset($placeDetails['error'])) {
// Handle error (e.g., log it)
} else {
update_option('google_rating', $placeDetails['rating']);
update_option('google_rating_total', $placeDetails['user_ratings_total']);
}
}
### Explanation:
– **Cron Jobs**: This method directly runs your PHP script at specified intervals without relying on the web server.
– **WordPress Cron**: This utilizes WordPress's scheduling system, which triggers events based on site traffic.
### Testing:
Make sure to test your implementation to ensure it works as expected. You can check if the options are being updated correctly and if the cron job is running at the intended intervals.
—
### **Option 1: Using SendGrid UI**
1. **Log in to your SendGrid account.**
2. **Go to Settings > Tracking Settings > Click Tracking** in the left-hand menu.
3. **Turn off click tracking**:
– Toggle the switch to disable click tracking. This will prevent SendGrid from replacing URLs in your emails with tracking links.
—
### **Option 2: Using SendGrid API**
If you're programmatically sending emails via the SendGrid API, you can disable click tracking by including the following configuration in your API payload:
{
"personalizations": [
{
"to": [
{
"email": "recipient@example.com"
}
],
"subject": "Subject Here"
}
],
"from": {
"email": "sender@example.com"
},
"content": [
{
"type": "text/plain",
"value": "Your email content here"
}
],
"tracking_settings": {
"click_tracking": {
"enable": false,
"enable_text": false
}
}
}
### Explanation:
– `enable: false` disables click tracking for HTML content.
– `enable_text: false` disables click tracking for plain text content.
—
### **Option 3: Via SendGrid SMTP**
If you're using SendGrid's SMTP service, you need to disable click tracking in the SendGrid UI as outlined in **Option 1** since SMTP does not support per-email configuration.
—
### Testing:
After disabling click tracking:
– Send a test email and inspect the links in the received email.
– Ensure that the URLs are not wrapped in SendGrid tracking links (e.g., `https://u1234567.ct.sendgrid.net/…`).
This approach ensures that your links remain intact and untracked.
—
### **Why This Happens**
1. **Missing Protocol**: If a URL in your email content is not fully qualified (e.g., `www.example.com` instead of `https://www.example.com`), SendGrid may prepend `http://` during the click-tracking transformation.
2. **Malformed URLs**: Links that don't conform to a valid URL structure might get altered.
3. **SendGrid Behavior**: By default, SendGrid rewrites URLs for tracking, which can introduce formatting issues if the input URLs aren't well-formed.
—
### **Solutions**
#### 1. **Always Use Fully Qualified URLs**
Ensure that all URLs in your email content include the correct protocol (`http://` or `https://`).
– **Incorrect**:
<a href="www.example.com">Visit our site</a>
– **Correct**:
<a href="https://www.example.com">Visit our site</a>
#### 2. **Disable Click Tracking**
If you don't need click tracking, disable it to avoid URL modifications:
– **In SendGrid UI**:
– Go to **Settings > Tracking Settings > Click Tracking** and toggle it off.
– **In API Calls**:
Add this to your API payload:
"tracking_settings": {
"click_tracking": {
"enable": false,
"enable_text": false
}
}
#### 3. **Use Escape Characters for Special Cases**
Ensure special characters in URLs are properly encoded. For example:
– Replace spaces with `%20`.
– Replace `&` with `&`.
#### 4. **Check Your Email Template**
Inspect your email templates to ensure:
– All `href` attributes contain valid, fully qualified URLs.
– No JavaScript links (e.g., `javascript:void(0);`) or placeholders (`#`) are present.
#### 5. **Debugging and Testing**
– Send a test email to yourself and inspect the links.
– Look for any patterns in the rewritten URLs.
– Use SendGrid's "Test Your Integration" feature under the "Settings > Mail Settings" to validate your email configuration.
—
### Example: SendGrid-Compatible Email
<!DOCTYPE html>
<html>
<body>
<p>Click the link below:</p>
<a href="https://www.example.com">Visit our website</a>
</body>
</html>
This ensures that SendGrid handles the link correctly.
—
By following these steps, you can prevent SendGrid from adding `http://` to URLs and ensure your links work as intended. If the problem persists despite these corrections, consider reaching out to SendGrid support with a detailed example of the issue.
—
### **1. Customize the Password Reset Email**
Use the `retrieve_password_message` filter to customize the content of the password reset email. Add the following code to your theme's `functions.php` file or a custom plugin:
add_filter('retrieve_password_message', 'custom_password_reset_email', 10, 4);
function custom_password_reset_email($message, $key, $user_login, $user_data) {
// Custom reset link
$reset_link = network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login');
// Customize the email message
$message = "Hello,nn";
$message .= "You requested to reset your password for the following account:nn";
$message .= "Username: $user_loginnn";
$message .= "To reset your password, click the following link:nn";
$message .= "$reset_linknn";
$message .= "If you did not request this, please ignore this email.nn";
$message .= "Thank you.";
return $message;
}
### **2. Fix HTTP/HTTPS Issues in the Reset Link**
If WordPress is generating `http://` URLs instead of `https://`, ensure the site is configured correctly:
– Go to **Settings > General** in the WordPress dashboard.
– Ensure both **WordPress Address (URL)** and **Site Address (URL)** use `https://`.
Alternatively, enforce HTTPS by adding the following code to your `wp-config.php` file:
define('FORCE_SSL_ADMIN', true);
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
$_SERVER['HTTPS'] = 'on';
}
### **3. Debugging Issues with the Password Reset Email**
– **Emails Not Being Sent**: Use a plugin like [WP Mail SMTP](https://wordpress.org/plugins/wp-mail-smtp/) to configure and test email delivery. This ensures emails are sent through a reliable service like SMTP or SendGrid.
– **Broken Links in Emails**: Inspect the generated reset link to ensure it contains the correct domain and format.
### **4. Use a Custom Email Template Plugin**
For more advanced customization, you can use a plugin like:
– **[WP Email Template](https://wordpress.org/plugins/wp-email-template/)**: Customize all WordPress emails with templates.
– **[Theme My Login](https://wordpress.org/plugins/theme-my-login/)**: Simplifies and customizes login, registration, and password reset functionality.
—
### **5. Replace the Default WordPress Email Sender**
If you'd like the email to come from a custom name or email address, use the following hooks:
add_filter('wp_mail_from', function() {
return 'no-reply@yourdomain.com'; // Replace with your email
});
add_filter('wp_mail_from_name', function() {
return 'Your Website Name'; // Replace with your site name
});
—
### **6. Test the Email**
– Test the password reset flow to ensure the email is formatted correctly and the link works as expected.
– Use tools like [MailHog](https://github.com/mailhog/MailHog) in your development environment to capture and inspect emails.
—
By customizing the email content and ensuring proper URL generation, you can provide a better user experience for password resets in WordPress.
—
### **1. Disable Click Tracking Globally via SendGrid UI**
1. **Log in to SendGrid.**
2. Navigate to **Settings > Tracking Settings > Click Tracking**.
3. **Turn off Click Tracking** by toggling the switch.
This will ensure that URLs in your emails are sent as-is without being rewritten for tracking.
—
### **2. Disable Click Tracking for Specific Emails via API**
If you want to disable click tracking for specific emails sent through the SendGrid API, include the following `tracking_settings` configuration in your API payload:
{
"personalizations": [
{
"to": [
{
"email": "recipient@example.com"
}
],
"subject": "Subject Here"
}
],
"from": {
"email": "sender@example.com"
},
"content": [
{
"type": "text/plain",
"value": "Your email content here with an unaltered link: https://www.example.com"
}
],
"tracking_settings": {
"click_tracking": {
"enable": false, // Disable tracking for HTML links
"enable_text": false // Disable tracking for plain text links
}
}
}
—
### **3. For SMTP Relay (WordPress or Other Applications)**
If you're sending emails through SendGrid's SMTP relay, click tracking cannot be selectively disabled via code. Instead, you need to disable click tracking globally in the **SendGrid UI** as described in **Step 1**.
—
### **4. Use Fully Qualified URLs**
Ensure all URLs in your email content are fully qualified (e.g., `https://www.example.com`) to minimize issues with malformed URLs during tracking.
—
### **5. Validate and Test**
– Send a test email and inspect the URLs to ensure they are not wrapped or altered.
– If you use custom email templates or third-party applications, verify they don't enforce their own tracking settings.
—
### **6. Contact SendGrid Support**
If URLs are still being altered despite disabling click tracking, it might be due to other SendGrid configurations. Reach out to their support team for assistance with identifying and disabling other potential URL-modifying features, such as spam checks or advanced link processing.
By disabling click tracking and ensuring proper email configuration, you can ensure that URLs remain unchanged in your emails.
—
### **Step 1: Disable Click Tracking in SendGrid**
Since WordPress sends emails through SendGrid, the simplest way to ensure URLs are not modified is to disable click tracking globally or for specific types of emails.
1. Log in to your **SendGrid account**.
2. Go to **Settings > Tracking Settings > Click Tracking**.
3. Turn off the toggle to disable click tracking globally.
—
### **Step 2: Use SendGrid API to Disable Click Tracking**
If you're sending emails through the SendGrid API (e.g., via an SMTP plugin like **WP Mail SMTP**), you can programmatically disable click tracking for the password reset email.
1. Open your WordPress theme's `functions.php` file or use a custom plugin.
2. Add the following code to disable tracking for password reset emails:
add_filter('wp_mail', function($args) {
// Check if the email is a password reset email
if (strpos($args['subject'], 'Password Reset') !== false) {
// Append SendGrid X-SMTPAPI header to disable click tracking
$args['headers'][] = 'X-SMTPAPI: {"filters": {"clicktrack": {"settings": {"enable": 0}}}}';
}
return $args;
});
—
### **Step 3: Ensure Fully Qualified URLs**
In the WordPress password reset email, the link is generated using the site's URL. Ensure your site is configured to use `https://` under **Settings > General**:
– WordPress Address (URL): `https://yourwebsite.com`
– Site Address (URL): `https://yourwebsite.com`
—
### **Step 4: Verify Password Reset URLs**
– Send yourself a password reset email.
– Check the received email to ensure the reset link is not altered or wrapped in SendGrid tracking links.
—
### **Step 5: Test SMTP Configuration**
If you are using an SMTP plugin like **WP Mail SMTP**, ensure it doesn't have settings that enforce tracking. Review the plugin settings:
1. Go to **WP Mail SMTP > Settings**.
2. Check the SendGrid integration settings and ensure tracking features are disabled.
—
By following these steps, the password reset email in WordPress will bypass SendGrid's click tracking, ensuring the reset URLs remain intact and functional.
// Check if the email is a password reset email
if (strpos($args['subject'], 'Password Reset') !== false) {
// Append SendGrid X-SMTPAPI header to disable click tracking
$args['headers'][] = 'X-SMTPAPI: {"filters": {"clicktrack": {"settings": {"enable": 0}}}}';
}
return $args;
});
Above gives fatal error
—
### **Corrected Code**
add_filter('wp_mail', function($args) {
// Check if the email is a password reset email
if (isset($args['subject']) && strpos($args['subject'], 'Password Reset') !== false) {
// Properly encode the X-SMTPAPI header
$smtpapi = json_encode([
'filters' => [
'clicktrack' => [
'settings' => [
'enable' => 0
]
]
]
]);
// Add the X-SMTPAPI header
$args['headers'][] = 'X-SMTPAPI: ' . $smtpapi;
}
return $args;
});
—
### **Explanation**
1. **Check if `subject` is set**:
– Prevents undefined index errors if the `subject` key is missing in `$args`.
2. **Format JSON Correctly**:
– Encodes the `X-SMTPAPI` payload as a valid JSON string using `json_encode()`.
3. **Add Headers Properly**:
– Ensures headers are appended correctly as a string, following WordPress's `wp_mail` header format.
—
### **Debugging Fatal Errors**
If you're still encountering issues:
– Add error logging to verify `$args` structure:
add_filter('wp_mail', function($args) {
error_log(print_r($args, true));
return $args;
});
– Check the logged data in your `wp-content/debug.log` (if logging is enabled) or server logs to ensure the expected data is present.
—
### **Testing**
1. Trigger a password reset email from WordPress.
2. Inspect the email headers to confirm the `X-SMTPAPI` header is present and click tracking is disabled.
Here’s the fixed code:
—
### **Corrected Code**
add_filter('wp_mail', function ($args) {
// Check if the email is a password reset email
if (isset($args['subject']) && strpos($args['subject'], 'Password Reset') !== false) {
// Properly encode the X-SMTPAPI header
$smtpapi = json_encode([
'filters' => [
'clicktrack' => [
'settings' => [
'enable' => 0
]
]
]
]);
// Ensure headers are initialized as an array
if (!isset($args['headers']) || !is_array($args['headers'])) {
$args['headers'] = [];
}
// Add the X-SMTPAPI header
$args['headers'][] = 'X-SMTPAPI: ' . $smtpapi;
}
return $args;
});
—
### **Key Fixes**
1. **Ensure `$args['headers']` is an Array**:
– Before using `$args['headers'][]`, check if it's already an array.
– If it's not set or is something else (like a string), initialize it as an empty array.
if (!isset($args['headers']) || !is_array($args['headers'])) {
$args['headers'] = [];
}
2. **Error Prevention**:
– Use `isset()` to ensure that `$args['subject']` exists before trying to access it.
– Added defensive checks to avoid accessing or modifying non-array data.
3. **PHP 8 Compatibility**:
– Ensured strict type handling to comply with PHP 8's stricter rules.
—
### **How It Works**
– The `wp_mail` filter modifies WordPress's email-sending behavior.
– This fix ensures that the `X-SMTPAPI` header is properly added without breaking the `$args` structure.
—
### **Testing**
1. Trigger a password reset email.
2. Confirm the email is sent successfully.
3. Check the email headers for the `X-SMTPAPI` entry:
X-SMTPAPI: {"filters":{"clicktrack":{"settings":{"enable":0}}}}
This should now work without errors in PHP 8.
// Check if the email is a password reset email
if (isset($args['subject']) && strpos($args['subject'], 'Password Reset') !== false) {
// Properly encode the X-SMTPAPI header
$smtpapi = json_encode([
'filters' => [
'clicktrack' => [
'settings' => [
'enable' => 0
]
]
]
]);
// Ensure headers are initialized as an array
if (!isset($args['headers']) || !is_array($args['headers'])) {
$args['headers'] = [];
}
// Add the X-SMTPAPI header
$args['headers'][] = 'X-SMTPAPI: ' . $smtpapi;
}
return $args;
});
above code still not prevent url rewrite
—
### **Step 1: Confirm SendGrid Settings**
Ensure that Click Tracking is **disabled** in your SendGrid account globally:
1. **Log in to SendGrid**.
2. Navigate to **Settings > Tracking Settings > Click Tracking**.
3. **Disable Click Tracking** globally by turning off the toggle.
This global setting overrides any per-email tracking unless explicitly re-enabled.
—
### **Step 2: Ensure SMTP Header Works with Your WordPress Setup**
The `X-SMTPAPI` header method may not work if your setup is not processing custom headers correctly. Verify the configuration:
1. Ensure you are using an SMTP plugin like **WP Mail SMTP** to send emails through SendGrid.
2. Check if the plugin supports adding custom headers. If not, you may need to modify how emails are sent.
For example, WP Mail SMTP allows custom headers to be included via its "Advanced Email Options."
—
### **Step 3: Use SendGrid's "Subuser" for WordPress Emails**
Create a dedicated subuser in SendGrid for WordPress emails and configure that subuser to have Click Tracking disabled:
1. Log in to your SendGrid account.
2. Navigate to **Settings > Subuser Management**.
3. Create a new subuser for WordPress emails and ensure Click Tracking is disabled for this subuser.
4. Update your SMTP settings in WordPress (e.g., via WP Mail SMTP) to use the new subuser credentials.
This ensures only WordPress emails are exempt from tracking.
—
### **Step 4: Alternative Hook to Modify WordPress Email Headers**
Use the `phpmailer_init` action to directly modify the `PHPMailer` object and add the `X-SMTPAPI` header. This can sometimes work better than `wp_mail` filtering:
add_action('phpmailer_init', function ($phpmailer) {
// Check if it's a password reset email
if (strpos($phpmailer->Subject, 'Password Reset') !== false) {
// Properly encode the X-SMTPAPI header
$smtpapi = json_encode([
'filters' => [
'clicktrack' => [
'settings' => [
'enable' => 0
]
]
]
]);
// Add the X-SMTPAPI header
$phpmailer->addCustomHeader('X-SMTPAPI', $smtpapi);
}
});
—
### **Step 5: Use an API-Based Approach**
If SMTP headers don't work, consider switching from SMTP to SendGrid's API for sending emails. The API allows precise control over email settings, including disabling click tracking on a per-email basis.
#### Example: Using WP Mail SMTP Pro's SendGrid Integration
1. Install **WP Mail SMTP Pro**.
2. Use the **SendGrid API** option for email delivery.
3. Add the following filter to disable click tracking:
add_filter('wp_mail_smtp_custom_headers', function ($custom_headers, $email_data) {
if (strpos($email_data['subject'], 'Password Reset') !== false) {
$custom_headers['X-SMTPAPI'] = json_encode([
'filters' => [
'clicktrack' => [
'settings' => [
'enable' => 0
]
]
]
]);
}
return $custom_headers;
}, 10, 2);
—
### **Testing**
1. Trigger a password reset email in WordPress.
2. Check the received email:
– Verify the `X-SMTPAPI` header is present.
– Confirm the URL is not rewritten by SendGrid.
—
If none of these solutions work, you may need to contact SendGrid support to ensure no account-level settings are enforcing click tracking for all emails.
—
### **1. Verify Click Tracking Settings in SendGrid**
Double-check your SendGrid account settings:
1. Log in to SendGrid.
2. Navigate to **Settings > Tracking Settings > Click Tracking**.
3. Ensure **Click Tracking** is **disabled globally**.
Sometimes, account-level overrides are applied to subusers or specific IP pools. Contact **SendGrid support** to verify that no such enforcement is active on your account.
—
### **2. Ensure Headers Are Being Sent**
Use the `phpmailer_init` action to directly interact with the `PHPMailer` object, which is responsible for sending emails in WordPress. Here’s an enhanced version:
add_action('phpmailer_init', function ($phpmailer) {
// Add custom headers only for password reset emails
if (strpos($phpmailer->Subject, 'Password Reset') !== false) {
// Properly encode the X-SMTPAPI header
$smtpapi = json_encode([
'filters' => [
'clicktrack' => [
'settings' => [
'enable' => 0
]
]
]
]);
// Add the X-SMTPAPI header
$phpmailer->addCustomHeader('X-SMTPAPI: ' . $smtpapi);
// Debug: Log headers to verify
error_log(print_r($phpmailer->getCustomHeaders(), true));
}
});
After adding this code:
1. Trigger a password reset email.
2. Check the `error_log` for the `X-SMTPAPI` header. Ensure it is present and correctly formatted.
—
### **3. Switch to SendGrid API for Email Delivery**
SMTP may have limitations on custom header support. The **SendGrid API** provides more granular control over email settings.
#### Using SendGrid's PHP SDK
Replace your SMTP plugin with direct API calls to SendGrid. Example for disabling click tracking:
require 'path/to/vendor/autoload.php'; // Load SendGrid library
function send_password_reset_email($to, $subject, $body) {
$email = new SendGridMailMail();
$email->setFrom("your-email@example.com", "Your Site");
$email->setSubject($subject);
$email->addTo($to);
$email->addContent("text/html", $body);
// Disable click tracking
$email->setTrackingSettings(
(new SendGridMailTrackingSettings())
->setClickTracking(
(new SendGridMailClickTracking())->setEnable(false)->setEnableText(false)
)
);
$sendgrid = new SendGrid('your-sendgrid-api-key');
try {
$response = $sendgrid->send($email);
error_log(print_r($response->statusCode(), true));
error_log(print_r($response->headers(), true));
error_log(print_r($response->body(), true));
} catch (Exception $e) {
error_log('Caught exception: '. $e->getMessage());
}
}
You can trigger this function for password reset emails, bypassing WordPress's default mailer.
—
### **4. Test URLs**
1. Send a password reset email.
2. Inspect the raw email headers in the received email (in Gmail or any email client).
3. Verify:
– The `X-SMTPAPI` header exists (for SMTP).
– The URL in the email is not rewritten.
—
### **5. Contact SendGrid Support**
If URLs are still being rewritten:
1. Verify with SendGrid support whether:
– Any account-level overrides are enforcing click tracking.
– Additional features (e.g., "Advanced Link Tracking") are active.
2. Request confirmation that `X-SMTPAPI` settings or API configurations are being honored for your account.
—
### **Fallback Option**
If SendGrid continues rewriting URLs despite all efforts, consider switching to another email delivery service like **Postmark**, **Amazon SES**, or **Mailgun**, which offer better control over email link behavior.
—
### **Step 1: Test with a Simple Non-WordPress Script**
Create a minimal PHP script to send an email via SendGrid and disable click tracking to isolate whether the issue is WordPress-specific:
#### PHP Test Script:
require 'path/to/vendor/autoload.php'; // Include SendGrid PHP SDK
$sendgrid = new SendGrid('your-sendgrid-api-key');
$email = new SendGridMailMail();
$email->setFrom("your-email@example.com", "Your Name");
$email->setSubject("Password Reset Test");
$email->addTo("recipient@example.com", "Recipient Name");
$email->addContent("text/html", "<p>Test email with click tracking disabled.</p>");
// Disable click tracking
$email->setTrackingSettings(
(new SendGridMailTrackingSettings())
->setClickTracking(
(new SendGridMailClickTracking())->setEnable(false)->setEnableText(false)
)
);
try {
$response = $sendgrid->send($email);
echo "Status Code: " . $response->statusCode() . "n";
echo "Response Body: " . $response->body() . "n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "n";
}
1. Replace `your-sendgrid-api-key` with your actual API key.
2. Run the script directly on your server:
php test-sendgrid.php
3. Check if the link in the test email is rewritten.
—
### **Step 2: Confirm Settings with SendGrid Support**
If the above script still rewrites URLs:
1. **Contact SendGrid Support**:
– Share your API request or SMTP headers.
– Ask if your account has **account-level overrides** for click tracking.
– Request explicit confirmation that `X-SMTPAPI` or API settings are being honored.
—
### **Step 3: Switch to an Alternative Email Provider**
If SendGrid is not honoring your configuration, consider migrating to an alternative provider. Some excellent options include:
#### **1. Postmark**
– Simple API with no forced link rewriting.
– Excellent for transactional emails like password resets.
#### **2. Amazon SES**
– Cost-effective and provides fine-grained control over email delivery.
#### **3. Mailgun**
– Supports disabling click tracking directly through its API.
—
### **Step 4: Use a Third-Party WordPress Plugin**
To bypass SendGrid entirely within WordPress, use a plugin like **WP Mail SMTP Pro** with an alternative email provider. Many plugins have direct integration with Postmark, Amazon SES, or Mailgun, offering simpler setups and better tracking control.
—
### **Final Option: Inline Links**
If SendGrid insists on rewriting links, as a last resort, use plaintext URLs in your password reset emails. Example:
add_filter('retrieve_password_message', function($message) {
return strip_tags($message); // Convert the HTML email to plain text
});
This approach ensures links are not tracked because they remain as plaintext, though it sacrifices HTML email formatting.