Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Created September 20, 2025 08:33
Show Gist options
  • Save sabrina-zeidan/33a7aa5961b5e4f129faf2c5cc872721 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/33a7aa5961b5e4f129faf2c5cc872721 to your computer and use it in GitHub Desktop.
Save all AJAX queries in 3 logs
<?php
add_action('shutdown', function() {
global $wpdb;
if ( empty($wpdb->queries) ) {
return;
}
$timestamp = date('Y-m-d H:i:s');
// Define log files
$log_full = WP_CONTENT_DIR . '/ajax-queries-full.log';
$log_filtered = WP_CONTENT_DIR . '/ajax-queries-filtered.log';
$log_options = WP_CONTENT_DIR . '/ajax-queries-options.log';
// Define exclusion patterns (extendable)
$exclude_patterns = [
$wpdb->prefix . 'options',
$wpdb->prefix . 'usermeta',
$wpdb->prefix . 'postmeta',
$wpdb->prefix . 'comments',
$wpdb->prefix . 'commentmeta',
$wpdb->prefix . 'users',
$wpdb->prefix . 'terms',
$wpdb->prefix . 'posts',
// families of tables
$wpdb->prefix . 'actionscheduler', // Action Scheduler
$wpdb->prefix . 'rocket', // WP Rocket
$wpdb->prefix . 'wpr', // WPR / Above the fold
$wpdb->prefix . 'wc_', // WooCommerce
$wpdb->prefix . 'woocommerce', // WooCommerce
];
// Normalize query so matching is easier
$normalize_query = function($query) {
$query = strtolower($query);
// normalize both \_ and \\_ to _
$query = str_replace(['\\_', '\_'], '_', $query);
$query = preg_replace('/\s+/', ' ', $query); // collapse whitespace
return $query;
};
// Check if query should be excluded
$is_excluded = function($query) use ($exclude_patterns, $normalize_query) {
$q = $normalize_query($query);
foreach ($exclude_patterns as $pattern) {
if (strpos($q, strtolower($pattern)) !== false) {
return true;
}
}
return false;
};
// Logs
$full_log = "=== {$timestamp} ===\n";
$filtered_log = "=== {$timestamp} ===\n";
$options_log = "=== {$timestamp} ===\n";
foreach ($wpdb->queries as $q) {
list($query, $time, $caller) = $q;
// Add to full log
$full_log .= sprintf(
"[%.5fs] %s\n-- Caller: %s\n\n",
$time,
$query,
$caller
);
// Add to filtered log
if (!$is_excluded($query)) {
$filtered_log .= sprintf(
"[%.5fs] %s\n-- Caller: %s\n\n",
$time,
$query,
$caller
);
}
// Add to options-only log
if (strpos($normalize_query($query), $wpdb->prefix . 'options') !== false) {
$options_log .= sprintf(
"[%.5fs] %s\n-- Caller: %s\n\n",
$time,
$query,
$caller
);
}
}
// Write files
file_put_contents($log_full, $full_log . "\n", FILE_APPEND);
file_put_contents($log_filtered, $filtered_log . "\n", FILE_APPEND);
file_put_contents($log_options, $options_log . "\n", FILE_APPEND);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment