As a developer, it might be useful to have WordPress highlight which database queries are being created. Especially if you are designing a custom solution for a customer, as we frequently do. To begin, just copy and paste the following code into your “wp-config.php” configuration file:
<?php
define( 'SAVEQUERIES', true );
?>
All WordPress Queries in a List
Add the following code to your theme to get a list of all database queries done for the current page.
<?php
if( current_user_can( 'administrator' ) ) {
global $wpdb;
echo '<pre>';
print_r( $wpdb->queries );
echo '</pre>';
}
?>
Setting SAVEQUERIES to true causes the wpdb global instance to save all database queries you perform, allowing you to view the amount of queries each page request makes to the database as well as the SQL used.
<?php
global $wpdb;
var_dump($wpdb->num_queries , $wpdb->queries);
?>
- $wpdb->queries: This will dump all SQL queires made to the database.
- $wpdb->num_queries: This will give you the number of queries made to the database.
You may also connect into “posts_request”. You may place the code in the “functions.php” file of your child theme.
<?php
add_filter( 'posts_request', 'cxc_debug_post_request_call_back' );
function cxc_debug_post_request_call_back( $sql_text ) {
$GLOBALS['CXC_debug'] = $sql_text;
return $sql_text;
}
?>
You may use “print r” in your theme’s wp_footer to produce the results displayed below:
<?php
add_action( 'wp_footer', 'cxc_footer_debug_post_request_call_back' );
function cxc_footer_debug_post_request_call_back(){
print_r( $GLOBALS['CXC_debug'] );
}
?>
Making Use of WP_Query
WP_Query creates a query for any item in the WordPress database.
WP_Query will occasionally insert additional information into the resulting SQL query. This function will be examined to ensure that we understand what it is communicating!
To do this, we just print the SQL string generated by WP_Query and inspect it for errors (see example below).
<?php
$query_args = array(
//Wp query Arguments
);
//Wp Query Results Variable
$results = new WP_Query( $query_args );
//show the wp query on screen
echo $results->request;
?>