Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use wp_query after changing database via new wpdb

I am trying to access custom posts from other database using wordpress. To do this i have changed the current $wpdb global variable:

$wpdb = new wpdb( $user, $pass, $db, $host );
$wpdb->show_errors();

This doesn't show any errors, but when I try to use WP_Query:

$args = array('post_type'=>'produtos');
$newloop = new WP_Query($args);    
                

I get the following error:

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM WHERE 1=1 AND .post_type = 'produtos' AND (.post_status = 'publish' OR .' at line 1]

SELECT SQL_CALC_FOUND_ROWS .ID FROM WHERE 1=1 AND .post_type = 'produtos' AND (.post_status = 'publish' OR .post_author = 1 AND .post_status = 'private') ORDER BY .post_date DESC LIMIT 0, 10


If i use $wpdb->get_results() and $wpdb->get_var() functions I can achieve what I want:

$wpdb = new wpdb( $user, $pass, $db, $host );
$rows = $wpdb->get_results("SELECT * FROM wp_posts where post_type='produtos' AND post_status='publish'");
foreach ($rows as $produto) {
   $id = $produto->ID;
   $title = $produto->post_title;
   $valor = $wpdb->get_var("SELECT meta_value FROM wp_postmeta WHERE meta_key = 'preco' AND post_id = $id");
   $url_id = $wpdb->get_var("SELECT meta_value from wp_postmeta where post_id = $id AND meta_key='_thumbnail_id'");
}

I am looking for an elegant solution to this problem.

like image 500
Bruno Rodrigues Avatar asked Sep 24 '13 20:09

Bruno Rodrigues


1 Answers

$wpdb = new wpdb( $user, $pass, $db, $host );

after creating the wpdb object, you need to set the table names, it's done by calling the set_prefix() method it will set up the table names.

 set_prefix( $prefix, $set_table_names = true )

if you check your sql error. the table names are empty. The default table prefix is 'wp_'.

solution:

$wpdb = new wpdb( $user, $pass, $db, $host );
$wpdb->set_prefix('wp_');

//then rest of your code..
like image 111
MortalViews Avatar answered Sep 18 '22 23:09

MortalViews