我想在单独的文件php中在WordPress中编写自定义查询。
我的班级:
<?php
require('../../../wp-blog-header.php');
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
//$this->db = new DB_Connect();
// $this->db->connect();
}
// destructor
function __destruct() {
}
//------------------------------------------------
function test(){
global $wpdb;
$q = "SELECT
wp_posts.ID as ID
FROM
wp_posts
WHERE 1 = 1
AND wp_posts.post_title LIKE '%s%'
AND wp_posts.post_type = 'post'
AND ((wp_posts.post_status = 'publish'))
ORDER BY wp_posts.post_date DESC
LIMIT 0, 5 ";
$arr = $wpdb->get_results($q);
foreach($arr as $a ){
echo $a['ID'];
}
}
}
?>
但test
函数不会返回(回显)任何内容。
我哪里错了?
更新
返回var_dump
$arr
:
> array(5) { [0]=> object(stdClass)#5354 (1) { ["ID"]=> string(4) "6533"
> } [1]=> object(stdClass)#5353 (1) { ["ID"]=> string(4) "5838" } [2]=>
> object(stdClass)#5352 (1) { ["ID"]=> string(4) "5786" } [3]=>
> object(stdClass)#5351 (1) { ["ID"]=> string(4) "5282" } [4]=>
> object(stdClass)#5350 (1) { ["ID"]=> string(4) "5230" } }
解决:
foreach($arr as $a ){
echo $a->ID;
}
答案 0 :(得分:1)
尝试使用以下代码:
<?php
require '../../../wp-load.php';
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
}
// destructor
function __destruct() {
}
function test(){
global $wpdb;
$q = "SELECT
wp_posts.ID as ID
FROM
wp_posts
WHERE 1 = 1
AND wp_posts.post_title LIKE '%s%'
AND wp_posts.post_type = 'post'
AND ((wp_posts.post_status = 'publish'))
ORDER BY wp_posts.post_date DESC
LIMIT 0, 5 ";
$arr = $wpdb->get_results($q);
foreach($arr as $a ){
echo $a['ID'];
}
}
}
?>
答案 1 :(得分:0)
你需要获得wordpress配置和数据库对象wp-load.php
。所以在你的课程中包含这个文件,然后就可以使用像这样的$wpdb
对象
require '../../../wp-load.php'; //change this path according to file
class DB_Functions {
public function init()
{
global $wpdb;
$wpdb->query('');
}
}