php - 如何在单独的文件中使用 $wpdb 变量

标签 php wordpress

我想在 WordPress 中的单独文件 php 中编写自定义查询。

我的类(class):

<?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 函数不会返回(回显)任何内容。 我哪里错了?

已更新

返回$arrvar_dump:

> 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;
   }

最佳答案

尝试使用以下代码:

<?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'];
       }
    }

}    
?>

关于php - 如何在单独的文件中使用 $wpdb 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965941/

相关文章:

php - 如何停用 Apache 中的通知?

php - 如何避免在子数据循环内调用数据库查询

PHP如何将图像转换为二进制并在jquery中使用ones和noughts作为变量

php - 短信到数据库

html - CSS - 选择器 - 复选框和标签之间的额外内容

php - 使用 CSS 和 php 查询参数在另一个 id 中选择一个 id

php - 如何解决这个错误 "Undefined variable: id"

php - "Class not found"尝试对 WordPress 插件使用 Composer 自动加载时

php - WordPress SQL 将字符串插入自定义字段

javascript - 如何使wordpress visual composer属性复选框最初被选中