問題描述

我正在開發一個不使用自定義帖子類型的插件,但是單獨的數據庫表。它是一個插件,顯示一系列具有鏈接的課程列表,導致不同的課程詳細信息頁面,用户然後可以訂閲課程。

在當前狀態下,我使用短代碼將插件數據導入具有自定義頁面模板 (page-courses.php) 的頁面。

我現在想要動態更改 the_title(),根據插件顯示的頁面 (課程列表,課程詳細信息頁面,表單,表單提交成功頁面) 。但是,只要使用以下過濾器執行此操作,頁腳中其他頁面的鏈接也會更改:

<?php

add_filter('the_title', 'custom_page_title');
function custom_page_title() {
    return 'Custom Title';
}

Edit

在 footer.php 中,我有一個包含與 wp_nav_menu()的腳註鏈接的功能,所以我可以在 Appearance> 菜單。但是使用上面的過濾器,頁腳中的所有鏈接也會更改為’Custom Title’ 。但是我只想更改頁面的標題,不會影響頁腳中的菜單鏈接。

嘗試添加條件標籤 in_the_loop(),腳註鏈接仍然受到影響,儘管它們不在循環中。

<?php

add_action( 'loop_start', 'set_custom_title' );
function set_custom_title() {
    if ( in_the_loop() ) {
        add_filter( 'the_title', 'custom_page_title' );
    }
}

function custom_page_title() {
    return 'Custom Title';
}

它類似於這個問題:filter the_title problem in nav,只是鏈接受影響在頁腳和 in_the_loop()不工作。

如何更改 the_title()隻影響當前頁面的標題顯示不影響頁腳中的鏈接?

編輯 2 – 解決方案

所以我終於得到它的工作:

<?php

add_action( 'loop_start', 'set_custom_title' );
function set_custom_title() {
    add_filter( 'the_title', 'wpse83525_filter_the_title', 10, 2 );
}

function wpse83525_filter_the_title( $title, $id ) {
    if ( 'page-listcourses.php' == get_post_meta( $id, '_wp_page_template', true ) ) {
        return 'Custom Title';
    }
    return $title;
}

文件 page-listcourses.php 是一個自定義帖子模板,我分配給靜態頁面,名為’Courses’ 。

我認為以前沒有工作,因為自定義帖子模板的靜態頁面和文件名的名稱是一樣的。

最佳解決方案

我會使用 is_page_template()條件:

if ( is_page_template( 'page-courses.php' ) ) {
    // The current page uses your
    // custom page template;
    // do something
}

Edit

您將在過濾器回調中使用此條件:

function wpse83525_filter_the_title( $title ) {
    if ( is_page_template( 'page-courses.php' ) ) {
        return 'Custom Title';
    }
    return $title;
}
add_filter( 'the_title', 'wpse83525_filter_the_title' );

現在,要隔離僅使用頁面模板的頁面的標題,可以利用傳遞給 the_title 的其他參數:$id 。由於您知道標題被過濾的帖子的 ID,您可以查詢_wp_page_template 後期元數據,並確保它等於您的頁面模板:

function wpse83525_filter_the_title( $title, $id ) {
    if ( 'page-courses.php' == get_post_meta( $id, '_wp_page_template', true ) ) {
        return 'Custom Title';
    }
    return $title;
}
add_filter( 'the_title', 'wpse83525_filter_the_title', 10, 2 );

編輯 2

如果要專門針對”Courses” 頁面,請使用 is_page()與頁面插槽'courses''Courses'的頁面標題:

function wpse83525_filter_the_title( $title ) {
    if ( is_page( 'Courses' ) ) {
        return 'Custom Title';
    }
    return $title;
}
add_filter( 'the_title', 'wpse83525_filter_the_title' );

雖然,我建議將 page-courses.php 更改為自定義頁面模板,這將使整個過程更加強大。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。