我在包含wp-load.php的自定义php文件中使用功能 have_posts() 。 但我有这个错误:
致命错误:第767行的C:\ xampp \ htdocs \ khanehkheshti \ wp-includes \ query.php中的null上调用成员函数have_posts()
php文件:
require_once( wp_normalize_path(ABSPATH).'wp-load.php');
public static function home() {
$query = new WP_Query(array(category_name => "img_news", 'posts_per_page' => '3' ));
$home = array();
$in = array();
while ( $query->have_posts() ) {
$query->the_post();
$home['title'] = get_the_title();
$home['content'] = get_the_content();
$home['img'] = the_post_thumbnail( array( 300, 260 ) );
$in[] = $home;
}
echo JSON_encode($in);
return $in;
}
答案 0 :(得分:0)
您应该在自定义PHP文件中初始化WordPress。您可以使用以下代码对其进行初始化。
/**
* WordPress initializing
*/
function find_wordpress_base_path()
{
$dir = dirname(__FILE__);
do
{
if(file_exists($dir.'/wp-config.php')) return $dir;
}
while($dir = realpath($dir.'/..'));
return NULL;
}
define('BASE_PATH', find_wordpress_base_path().'/');
define('WP_USE_THEMES', false);
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require(BASE_PATH.'wp-load.php');
// Now you have access to WordPress functions here
答案 1 :(得分:0)
尝试将wp-load.php替换为wp-blog-header.php。这是示例代码:
define('WP_USE_THEMES', false);
require_once('PATHHERE/wp-blog-header.php');
public static function home() {
$query = new WP_Query(array(category_name => "img_news", 'posts_per_page' => '3' ));
$home = array();
$in = array();
while ( $query->have_posts() ) {
$query->the_post();
$home['title'] = get_the_title();
$home['content'] = get_the_content();
$home['img'] = the_post_thumbnail( array( 300, 260 ) );
$in[] = $home;
}
echo JSON_encode($in);
return $in;
}