Use wp_query after changing database via new wpdb
我正在尝试使用 wordpress 从其他数据库访问自定义帖子。为此,我更改了当前的 $wpdb 全局变量:
1
2 |
$wpdb = new wpdb( $user, $pass, $db, $host );
$wpdb->show_errors(); |
这不会显示任何错误,但是当我尝试使用 WP_Query:
1
2 |
$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() 函数,我可以实现我想要的:
1
2 3 4 5 6 7 8 |
$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?你到底想达到什么目的?什么是更大的图景,这使它有必要?
- 我想在移动网站的主网站(一个带有自己的 wordpress 安装的子域)中使用帖子类型 \\’produtos\\’。我在这个线程中读到我应该覆盖 $wpdb 因为 WP_Query 使用它。
- 我不确定,但你的两个 wordpress 是相同的版本
1
|
$wpdb = new wpdb( $user, $pass, $db, $host );
|
创建wpdb对象后,需要设置表名,通过调用set_prefix() method来设置表名。
1
|
如果你检查你的 sql 错误。表名是空的。默认表前缀是 ‘wp_’.
解决方案:
1
2 3 4 |
- 避免像谢谢这样的评论。好吧,经过大约 5 个小时的连续战斗,这解决了我的问题..谢谢,这么多!
- 这对我不起作用!两个数据库在同一台服务器上,但仍然无法正常工作!顺便说一句,任何建议都使用完全相同的代码。
来源:https://www.codenong.com/18991556/