― I’M SHISHIR RAVEN

WEBSITE & App Builder

Lorem Ipsum is simply dummy text of the printing and type setting industry. Lorem Ipsum has been the industry’s standard dummy text.

How to see the SQL Queries being executed in WordPress REST API

You can add the following filter and you will see the queries in the Response Header.

// Define a global variable to store SQL queries
global $wp_rest_api_queries;
$wp_rest_api_queries = array();

// Hook to capture SQL queries
add_filter('query', 'capture_rest_api_queries');

function capture_rest_api_queries($query) {
    global $wp_rest_api_queries;

    // Only capture queries made during REST API requests
    if (defined('REST_REQUEST') && REST_REQUEST) {
        $wp_rest_api_queries[] = $query;
    }

    return $query;
}

// Hook to add captured SQL queries to REST API response headers
add_filter('rest_post_dispatch', 'add_sql_queries_to_header', 10, 3);

function add_sql_queries_to_header($response, $server, $request) {
    global $wp_rest_api_queries;

    // Add SQL queries to response headers
    $response->header('X-SQL-Queries', json_encode($wp_rest_api_queries));

    return $response;
}

Posted

in

by

Tags: