I need to get query results after they have executed

    add_filter('query', 'query_recorder_wrapper_wptc');

I use query filter to get all queries before they executed, I also want after they executed. I exhausted of searching this.

Is there any hooks or script for this?



Extending the wpdb class

We can create the db.php file under wp-content/ directory to override the wpdb class to our needs.

I checked this site for such examples and found one by @MarkKaplun here.

Here's an example how one can get access to the last result, after each query has run:

 * db.php - Override the global $wpdb object to collect all query results
namespace WPSE\Question242685;

class DB extends \wpdb
    public function __construct( $dbuser, $dbpassword, $dbname, $dbhost )
        // Parent constructor
        parent::__construct( $dbuser, $dbpassword, $dbname, $dbhost );

    public function query( $query )
        // Parent query
        $val = parent::query( $query );

        // Edit this to your needs
        // Warning: It can be slow and resource demanding to collect all results 
        if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
            // do something with $this->last_result;

        return $val;

} // end class

// Override the global wpdb object

Here we assume the SAVEQUERIES is defined as true in the wp-config.php file.

Note that collecting all the results can be resource demanding, so you better only test this on a dev install.


What you can do is use the wp action with the global variable $wp_query, like so:

function all_queried_items(){

    global $wp_query;

    $all_queried_posts = $wp_query->posts;


add_action('wp', 'all_queried_items');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.