Question

I am trying to get the Query data with backtrace by extending the wpdb class and overwriting the Custom query function. The code is working fine if i Create a Symlink of db.php but is not working directly if i try to do it in a Plugin file.

The Code is :

<?php

if ( ! defined( 'SAVEQUERIES' ) ) {
  define( 'SAVEQUERIES', true );
}

class My_DB extends wpdb {
  function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
    parent::__construct( $dbuser, $dbpassword, $dbname, $dbhost );
  }

  function query( $query ) {
    if ( ! $this->ready ) {
      if ( isset( $this->check_current_query ) ) {
        $this->check_current_query = true;
      }
      return false;
    }

    if ( $this->show_errors ) {
      $this->hide_errors();
    }

    $result = parent::query($query);
    $result = parent::query( $query );
    if ( ! SAVEQUERIES ) {
      return $result;
    }

    $i = $this->num_queries - 1;
    $this->queries[$i][3] = debug_backtrace(false);
    $this->queries[$i][4] = $this->time_start;
    $this->queries[$i][5] = $result;

    return $result;
  }
}

$wpdb = new My_DB( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );

?>
Was it helpful?

Solution

Calling wp_set_wpdb_vars() after replacing $wpdb will probably do the trick.

$wpdb = new My_DB();
wp_set_wpdb_vars();

However, the only officially supported way to replace wpdb is to place a db.php in wp-content folder. If you can, I would suggest to do that.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top