WordPress虛擬頁面 - "嘗試取得非物件的屬性'post_type'"
P粉265724930
P粉265724930 2024-01-16 12:01:22
0
1
404

我正在建立一個 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粉265724930
P粉265724930

全部回覆(1)
P粉002023326

如果您嘗試在 WP 6.1 中使用虛擬頁面,您將無法再擁有貼文 ID。這條線導致它破裂。

$post->ID = -999;

#
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!