通过新的wpdb更改数据库后使用wp_query [英] Use wp_query after changing database via new wpdb

查看:59
本文介绍了通过新的wpdb更改数据库后使用wp_query的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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);    
                

我收到以下错误:

WordPress数据库错误:[您的SQL语法有误;请查看与您的MySQL服务器版本相对应的手册,以获取在'FROM WHERE 1 = 1 AND ..post_type ='produtos'AND(.post_status ='publish'OR.',在第1行附近)附近使用的正确语法.

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]

从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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆