0

I'm attempting to retrieve data from a separate WordPress installation on the same server. I'm able to use the wpdb class to successfully connect to the alternate database and get results, however, I can't seem to use the class methods with my newly created database.

For clarification: I have 2 Wordpress installations. I am attempting to retrieve posts from one database into a page from the other installation. The new database is another basic Wordpress database.

This works and brings me data:

$query = "
SELECT *
FROM wp_posts
WHERE post_type='post'
AND post_status='publish'
";

$rows = $newdb->get_results($query, ARRAY_A);

This fails to get results:

$query = "
SELECT *
FROM $newdb->posts
WHERE post_type='post'
AND post_status='publish'
";

$rows = $newdb->get_results($query, ARRAY_A);

I'm using the following to connect the database:

$newdb = new wpdb('username','password','database','localhost');

All of the material I've found uses the wpdb methods to interact with the new database and I'm having trouble making my queries more complex without the ability to use them.

What am I missing?

1
  • 1
    Would you mind explaining (in an edit) what the new DB is, what you need it for and how it's structured?
    – kaiser
    Commented Sep 20, 2014 at 1:10

1 Answer 1

0

After instantinating a wpdb the instace vars holding the table names are still not present. You need to call the set_prefix() method, in order to setup all table names according to your other wordpress table prefix. (Very likely this will be wp_ in your case).

$newdb = new wpdb( DB_USER , DB_PASSWORD , DB_NAME , DB_HOST );
var_dump($newdb->posts); // NULL = not good

$newdb->set_prefix('wp_');
var_dump($newdb->posts); // 'wp_posts' yeah!
0

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.