WordPress中点击'email-link'类链接时发送含访客信息的邮件通知方法
Hey there! Let's walk through setting up that email notification feature you need—where clicking any link with the email-link class triggers an alert email with the visitor's IP, city, and country. Here's a straightforward, step-by-step implementation:
Step 1: Add Frontend Click Listener
First, we need to detect when someone clicks your target links and send a request to the WordPress backend to trigger the email. You can do this with vanilla JavaScript:
Either create a new file link-notification.js in your theme's js folder, or paste this directly into your theme's footer.php (wrap it in <script> tags):
document.addEventListener('DOMContentLoaded', function() { // Grab all links with the 'email-link' class const emailLinks = document.querySelectorAll('.email-link'); emailLinks.forEach(link => { link.addEventListener('click', function(e) { // Prevent immediate redirect to ensure the email request sends first e.preventDefault(); const targetUrl = this.href; // Send AJAX request to WordPress backend fetch(wpAjax.ajax_url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-WP-Nonce': wpAjax.nonce }, body: `action=send_link_click_notification&link_url=${encodeURIComponent(targetUrl)}` }) .then(() => { // Once the request is sent, redirect to the original link window.location.href = targetUrl; }) .catch(err => { console.error('Notification failed to send:', err); // Still redirect even if there's an error window.location.href = targetUrl; }); }); }); });
Step 2: Set Up Backend AJAX Handler
Next, add this PHP code to your theme's functions.php file. This handles the AJAX request, collects visitor data, and sends the email:
// Register AJAX actions for both logged-in and guest users add_action('wp_ajax_send_link_click_notification', 'send_link_click_notification'); add_action('wp_ajax_nopriv_send_link_click_notification', 'send_link_click_notification'); function send_link_click_notification() { // Verify the request is legitimate with a nonce check_ajax_referer('link_notification_nonce', 'X-WP-Nonce'); // Get the clicked link URL from the request $link_url = isset($_POST['link_url']) ? urldecode($_POST['link_url']) : 'Unknown Link'; // Helper function to get the visitor's real IP (handles proxies like Cloudflare) function get_visitor_ip() { $ip = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]); } return $ip; } $visitor_ip = get_visitor_ip(); // Helper function to get visitor's city and country using a free API function get_visitor_location($ip) { // We'll use ip-api.com (free for non-commercial use, check their terms) $api_response = wp_remote_get("http://ip-api.com/json/{$ip}"); if (is_wp_error($api_response)) { return 'Unknown Location'; } $location_data = json_decode(wp_remote_retrieve_body($api_response), true); if ($location_data['status'] === 'success') { return "{$location_data['city']}, {$location_data['country']}"; } else { return 'Unknown Location'; } } $visitor_location = get_visitor_location($visitor_ip); // Configure email details $recipient_email = 'your-notification-email@example.com'; // Replace with your email $email_subject = "Link Click Alert: {$link_url}"; $email_message = "A visitor clicked the following link:\n\n"; $email_message .= "Link URL: {$link_url}\n"; $email_message .= "Visitor IP: {$visitor_ip}\n"; $email_message .= "Location: {$visitor_location}\n"; $email_headers = array('Content-Type: text/plain; charset=UTF-8'); // Send the email using WordPress' built-in function wp_mail($recipient_email, $email_subject, $email_message, $email_headers); // Send a success response back to the frontend wp_send_json_success(array('message' => 'Notification sent')); } // Enqueue the frontend script and pass AJAX credentials add_action('wp_enqueue_scripts', 'enqueue_link_notification_assets'); function enqueue_link_notification_assets() { // Enqueue the script (adjust the path if you placed it elsewhere) wp_enqueue_script( 'link-notification-script', get_template_directory_uri() . '/js/link-notification.js', array(), '1.0', true // Load in footer for better performance ); // Pass AJAX URL and nonce to the frontend script wp_localize_script('link-notification-script', 'wpAjax', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('link_notification_nonce') )); }
Key Notes & Adjustments
- Replace the Recipient Email: Make sure to swap
your-notification-email@example.comwith the email where you want to receive alerts. - IP API Limits: The free ip-api.com service has rate limits (150 requests/minute). If you get high traffic, consider switching to a paid geolocation service or install a plugin like GeoIP Detection to handle location data locally.
- Testing: Click one of your
email-linklinks and check your inbox. If it doesn't arrive, check your spam folder and use your browser's developer tools (Console tab) to debug any JavaScript errors. - Privacy Compliance: If you're collecting visitor IPs and location data, ensure you disclose this in your site's privacy policy to comply with regulations like GDPR.
内容的提问来源于stack exchange,提问作者Mark Anderson

