4

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 );

?>

1 Answer 1

5

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.

1
  • It worked... but i need to drill more. Thanks for your reply. Saved my day. Commented Aug 10, 2018 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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