Wordpress 数据库查询错误 Call to a member function get_results() on null

在插件中的一个文件使用如下代码,无法查询

<body>   
        <?php
        global $wpdb;
        $sql = "";
        $sql = "SELECT * FROM emgAdmin";
        $sql = "$sql INNER JOIN wp_posts ON wp_posts.ID = emgAdmin.ID_OfPost ";        
        $ArrResult = $wpdb->get_results($sql);
        while ($emgAdminResult = mysql_fetch_object($ArrResult)) {
            echo($emgAdminResult->post_date);
        }
        ?>
    </body>

错误如下:

 

处理如下:

  1. 删除 global $wpdb
  2. 将以下代码添加到文件顶部
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );

 

完整代码如下:

<?php
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
$sql = "";
$sql = "SELECT * FROM emgAdmin";
$sql = "$sql INNER JOIN wp_posts ON wp_posts.ID = emgAdmin.ID_OfPost ";        
$ArrResult = $wpdb->get_results($sql);
while ($emgAdminResult = mysql_fetch_object($ArrResult)) {
    echo($emgAdminResult->post_date);
}
?>

 

posted @ 2019-02-11 18:35  Ryan_zheng  阅读(777)  评论(0编辑  收藏  举报