在WordPress中,一個頁面調(diào)用另一個頁面的內(nèi)容通常不是WordPress設(shè)計的直接功能,因為WordPress的頁面和內(nèi)容通常是獨立管理的。不過,你可以通過幾種方法來實現(xiàn)這一需求:

1. 使用WordPress的短代碼(Shortcodes)

你可以創(chuàng)建一個自定義的短代碼,該短代碼通過WordPress的API獲取指定頁面的內(nèi)容,并將其輸出到當(dāng)前頁面。這通常涉及到使用WP_Query類來查詢指定頁面的內(nèi)容。

步驟:

創(chuàng)建短代碼函數(shù):在你的functions.php文件(位于主題的根目錄下)中,添加一個函數(shù)來定義你的短代碼。這個函數(shù)將使用WP_Query來獲取另一個頁面的內(nèi)容,并返回這些內(nèi)容。

function my_wdp_shortcode_content() {
//Set query parameters to obtain specific pages
    $args = array(
        'post_type' => 'page',
        'name'      => '目標(biāo)頁面的slug', //Or use 'page_id'=>123
    );
    //Create query
    $query = new WP_Query( $args );
    // wodepress.com Check if there are any results
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            //Output page content
            the_content();
        }
        wp_reset_postdata(); //Reset query data
    }
}
add_shortcode( 'custom_page_content', 'my_wdp_shortcode_content' );

在頁面中使用短代碼:在你的WordPress編輯器中,只需在需要顯示另一個頁面內(nèi)容的地方添加[custom_page_content]短代碼即可。

2. 使用PHP模板標(biāo)簽和條件語句

如果你正在編輯一個模板文件(如page-template.php),你也可以直接在模板文件中使用WP_Query來調(diào)用另一個頁面的內(nèi)容。

示例:

//In your template file
$args = array(
    'post_type' => 'page',
    'name'      => '目標(biāo)頁面的slug',
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Wodepress.com Output page title and content
        the_title('<h2>', '</h2>');
        the_content();
    }
    wp_reset_postdata();
}

3. 使用WordPress的REST API

如果你的WordPress站點啟用了REST API(在較新版本的WordPress中默認(rèn)啟用),你也可以通過AJAX請求從前端JavaScript代碼中調(diào)用另一個頁面的內(nèi)容。

步驟:

使用WordPress REST API獲取頁面內(nèi)容。

在前端JavaScript中處理這些數(shù)據(jù),并將其插入到DOM中。

注意事項

當(dāng)你從一個頁面調(diào)用另一個頁面的內(nèi)容時,請確保你遵守了版權(quán)和內(nèi)容使用政策。

過度使用這種方法可能會導(dǎo)致頁面加載時間增加,特別是當(dāng)被調(diào)用的頁面包含大量內(nèi)容或復(fù)雜查詢時。

使用短代碼或模板標(biāo)簽時,請確保你理解了WordPress的查詢機制和性能影響。