我正在尝试使用 wordpress 从其他数据库访问自定义帖子。为此,我更改了当前的 $wpdb
全局变量:
$wpdb = new wpdb( $user, $pass, $db, $host );
$wpdb->show_errors();
这没有显示任何错误,但是当我尝试使用 WP_Query
时:
$args = array('post_type'=>'produtos');
$newloop = new WP_Query($args);
我收到以下错误:
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
如果我使用 $wpdb->get_results()
和 $wpdb->get_var()
函数,我可以实现我想要的:
$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'");
}
我正在寻找一个优雅的解决方案来解决这个问题。
最佳答案
$wpdb = new wpdb( $user, $pass, $db, $host );
创建 wpdb 对象后,您需要设置表名,这是通过调用 set_prefix() 方法
完成的,它将设置表名。
set_prefix( $prefix, $set_table_names = true )
如果你检查你的sql错误。表名是空的。默认表前缀是 'wp_'
。
解决方法:
$wpdb = new wpdb( $user, $pass, $db, $host );
$wpdb->set_prefix('wp_');
//then rest of your code..
关于mysql - 通过新的 wpdb 更改数据库后使用 wp_query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18991556/