问题描述
我正在尝试使用wordpress访问来自其他数据库的自定义帖子.为此,我更改了当前的$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();
这不会显示任何错误,但是当我尝试使用WP_Query
时:
This doesn't show any errors, but when I try to use WP_Query
:
$args = array('post_type'=>'produtos');
$newloop = new WP_Query($args);
我收到以下错误:
从1 = 1处选择SQL_CALC_FOUND_ROWS .ID并且.post_type ='produtos'AND(.post_status ='publish'或.post_author = 1和.post_status ='private')ORDER BY .post_date DESC LIMIT 0,10
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()
函数,我可以实现我想要的:
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 );
在创建wpdb对象之后,您需要设置表名,这是通过调用set_prefix() method
来完成的,它将设置表名.
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 )
如果您检查sql错误.表名称为空.默认表前缀为'wp_'
.
if you check your sql error. the table names are empty. The default table prefix is 'wp_'
.
解决方案:
$wpdb = new wpdb( $user, $pass, $db, $host );
$wpdb->set_prefix('wp_');
//then rest of your code..
这篇关于通过新的wpdb更改数据库后使用wp_query的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!