首页 > 解决方案 > 如何在自定义 php 文件中使用 wordpress 的功能

问题描述

我在包含 wp-load.php 的自定义 php 文件中使用函数 have_posts() 。但我有这个错误:

致命错误:在第 767 行的 C:\xampp\htdocs\khanehkheshti\wp-includes\query.php 中调用一个成员函数 have_posts() on null

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



}

标签: wordpressfunction

解决方案


尝试用 wp-blog-header.php 替换 wp-load.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;

} 

推荐阅读