亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

我正在建立一個(gè) WordPress 插件,它使用虛擬頁(yè)面來(lái)顯示從 API 獲取的資料。

設(shè)定相對(duì)簡(jiǎn)單。我對(duì)外掛程式要工作的 URL 有一個(gè)重寫規(guī)則,當(dāng)我點(diǎn)擊特定的 query_vars 時(shí),我會(huì)啟動(dòng)虛擬頁(yè)面。

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

此程式碼執(zhí)行了預(yù)期的操作,即顯示包含我需要的內(nèi)容的虛擬頁(yè)面,但我在 PHP 8.0 中收到警告:

"Attempt to read property "post_type" on null"

我相信這裡的執(zhí)行順序是錯(cuò)誤的,因?yàn)槲以?xdebug 中得到空的 $post 和 $wp_query。我猜測(cè)虛擬頁(yè)面函數(shù)執(zhí)行得太早了。

我嘗試調(diào)試這個(gè)問(wèn)題很長(zhǎng)時(shí)間,但不幸的是我缺乏後端/WordPress 知識(shí)。

如果有人能提供幫助,我將更加感激。

P粉265724930
P粉265724930

全部回覆(1)
P粉002023326

如果您嘗試在 WP 6.1 中使用虛擬頁(yè)面,您將無(wú)法再擁有貼文 ID。這條線導(dǎo)致它破裂。

$post->ID = -999;

#
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板