Sometimes, as a developer, it may be beneficial to have WordPress display is what database queries are being generated. Particularly if you are developing a custom solution for a client as we do often. To begin, simply add the follow code below to your “wp-config.php” configuration file:
define( 'SAVEQUERIES', true );
List All WordPress Queries
To list all of the database queries made for the current page, add the following code to your theme. See the WordPress Codex documentation for more details.
if( current_user_can( 'administrator' ) )
echo '<pre>' . print_r( $wpdb->queries ) . '</pre>';
In addition, you can hook into “posts_request“. You can put the code inside your child theme’s “functions.php” file.
add_filter( 'posts_request', 'debug_post_request' ); //debugging sql query of a post
function debug_post_request( $sql_text )
$GLOBALS['debugENDURTECH'] = $sql_text; //intercept and store the sql
Within your theme’s footer, you can use “print_r” to output the results as shown below:
print_r( $GLOBALS['debugENDURTECH'] );
If you are only interested in displaying what a loop is processing you can use something like the below:
add_filter( 'posts_request', 'dump_request' );
function dump_request( $input )
var_dump( $input );
WP_Query builds a query for any type of object within the WordPress database.
Sometimes WP_Query will pass additional information into the generated SQL query. It is this function that we will want to inspect to make sure we know what it is actually transmitting!
To do this, we simply print out the SQL string WP_Query built and check it for any issues (see example below).
$query_args = array(
//your query arguments
//set results variable
$results = new WP_Query( $query_args );
//show the query on screen
If this article was helpful please take a moment to like us on Facebook, share this on your social media or buy us a cup of coffee.