Using WordPress ‘log_query_custom_data’ PHP filter

The log_query_custom_data WordPress PHP Filter allows you to modify the custom data logged alongside a SQL query.

Usage

add_filter('log_query_custom_data', 'my_custom_log_query_data', 10, 5);

function my_custom_log_query_data($query_data, $query, $query_time, $query_callstack, $query_start) {
    // your custom code here

    return $query_data;
}

Parameters

  • $query_data (array) – Custom query data.
  • $query (string) – The SQL query.
  • $query_time (float) – Total time spent on the query, in seconds.
  • $query_callstack (string) – Comma-separated list of the calling functions.
  • $query_start (float) – Unix timestamp of the time at the start of the query.

More information

See WordPress Developer Resources: log_query_custom_data

Examples

Add the user ID to the logged data

Add the current user ID to the query data, so you can see which user triggered the query.

function add_user_id_to_query_data($query_data, $query, $query_time, $query_callstack, $query_start) {
    $current_user_id = get_current_user_id();
    $query_data['user_id'] = $current_user_id;

    return $query_data;
}
add_filter('log_query_custom_data', 'add_user_id_to_query_data', 10, 5);

Log the current page URL

Log the current page URL alongside the query data.

function log_page_url($query_data, $query, $query_time, $query_callstack, $query_start) {
    $current_url = home_url($_SERVER['REQUEST_URI']);
    $query_data['current_url'] = $current_url;

    return $query_data;
}
add_filter('log_query_custom_data', 'log_page_url', 10, 5);

Log memory usage

Log the memory usage at the time of the query.

function log_memory_usage($query_data, $query, $query_time, $query_callstack, $query_start) {
    $memory_usage = memory_get_usage();
    $query_data['memory_usage'] = $memory_usage;

    return $query_data;
}
add_filter('log_query_custom_data', 'log_memory_usage', 10, 5);

Log the query type

Determine and log the type of SQL query (e.g., SELECT, INSERT, UPDATE).

function log_query_type($query_data, $query, $query_time, $query_callstack, $query_start) {
    $query_type = strtoupper(substr(trim($query), 0, 6));
    $query_data['query_type'] = $query_type;
    return $query_data;
}
add_filter('log_query_custom_data', 'log_query_type', 10, 5);