首页  >  问答  >  正文

WordPress虚拟页面 - "尝试获取非对象的属性'post_type'"

我正在构建一个 WordPress 插件,它使用虚拟页面来显示从 API 获取的数据。

设置相对简单。我对插件要工作的 URL 有一个重写规则,当我点击特定的 query_vars 时,我会启动虚拟页面。

public function __construct()
{

    require_once plugin_dir_path(__FILE__).'vendor/autoload.php';

    add_action('init', [$this, 'rewrite_rule'], 1);

    // add query vars
    add_action('query_vars', [$this, 'add_query_vars_filter'], 1);

    // virtual page init
    add_filter('the_posts', [$this, 'virtual_page'], 1);

}
public function virtual_page($posts)
{

    global $wp, $wp_query;

    if (!empty(get_query_var('plugin'))) {
        $plugin = get_query_var('plugin');
    }

    if (!empty($plugin)) {

        $post = new stdClass();
        $post->post_author = 1;
        $post->post_name = 'lorem ipsum';
        $post->guid = get_bloginfo('wpurl').'/';

        $post->post_title = 'title';
        $post->post_content = 'content';

        $post->ID = -999;
        $post->post_type = 'page';
        $post->post_status = 'static';
        $post->comment_status = 'closed';
        $post->ping_status = 'open';
        $post->comment_count = 0;
        $post->post_date = current_time('mysql');
        $post->post_date_gmt = current_time('mysql', 1);
        $posts = NULL;
        $posts[] = $post;

        $wp_query->is_page = true;
        $wp_query->is_single = false;

        $wp_query->is_singular = true;
        $wp_query->is_home = false;
        $wp_query->is_archive = false;
        $wp_query->is_category = false;

        unset($wp_query->query["error"]);
        $wp_query->query_vars["error"] = "";
        $wp_query->is_404 = false;

        remove_filter('the_content', 'wpautop');
        remove_filter('the_excerpt', 'wpautop');

        return $posts;
    }
}

此代码执行了预期的操作,即显示包含我需要的内容的虚拟页面,但我在 PHP 8.0 中收到警告:

"Attempt to read property "post_type" on null"

我相信这里的执行顺序是错误的,因为我在 xdebug 中得到空的 $post 和 $wp_query。我猜测虚拟页面函数执行得太早了。

我尝试调试这个问题很长时间,但不幸的是我缺乏后端/WordPress 知识。

如果有人能提供帮助,我将更加感激。

P粉265724930P粉265724930251 天前408

全部回复(1)我来回复

  • P粉002023326

    P粉0020233262024-01-17 10:01:10

    如果您尝试在 WP 6.1 中使用虚拟页面,您将无法再拥有帖子 ID。这条线导致它破裂。

    $post->ID = -999;

    回复
    0
  • 取消回复