How To Print Query In WordPress

If you’ve ever wanted to see the raw SQL query that WordPress executes when retrieving posts or other data from the database, you’re in the right place. In this blog post, we will cover how to print SQL queries in WordPress, which can be useful for debugging or understanding what’s going on under the hood.

Using the query() Method in WP_Query

WordPress uses the WP_Query class to build and execute queries. One of the methods in this class, called query(), can be used to see the actual SQL query string. To use it, you’ll need to have an instance of the WP_Query class.

For example, let’s say you want to query for all the posts in the ‘news’ category:

    $args = array(
        'category_name' => 'news',
    );

    $query = new WP_Query($args);
    

Now that you have an instance of WP_Query, you can use the query() method to print the SQL query:

    echo $query->request;
    

This will output the raw SQL query, which will look something like this:

SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1  AND ( wp_term_relationships.term_taxonomy_id IN (2) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10

Using the posts_request Filter

Another way to print the SQL query in WordPress is by using the posts_request filter. This filter allows you to modify the SQL query before it’s executed by the database.

To print the SQL query, you can simply create a function that takes the query as an argument and returns it unchanged, while also echoing the query. Then, you can add this function to the posts_request filter.

Here’s an example:

    function print_sql_query($query) {
        echo '<pre>' . $query . '</pre>';
        return $query;
    }
    add_filter('posts_request', 'print_sql_query');
    

With this code added to your WordPress theme’s functions.php file or a custom plugin, you’ll see the SQL query printed on the page every time a query is executed. If you only want to see the query for a specific instance of WP_Query, you can remove the filter after the query has executed:

    add_filter('posts_request', 'print_sql_query');
    $query = new WP_Query($args);
    remove_filter('posts_request', 'print_sql_query');
    

Conclusion

Printing SQL queries in WordPress can be a helpful debugging tool and can give you a better understanding of how WordPress interacts with the database. By using the query() method in WP_Query or the posts_request filter, you can easily output the raw SQL query for any query in your WordPress site. Happy debugging!