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.
$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..
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With