問題描述

當我在”the loop”(存檔頁面等) 中,如何強制所有文章的 teasers /摘錄,不管它們是否包含<!--more--> 標籤?

細節:

我從_s 模板開始,它使用 content.php 模板顯示部落格文章內容,該模板稱為 the_content()函式。此功能檢查該帖子,並嘗試找到<!--more--> 標籤。如果找到該標籤,則返回一個預告片和一個更多的連結,如果不是隻輸出整個帖子。

我想保留第一部分,如果內容作者使用<!--more--> 標籤,但是如果他/她忘記了它,我想自動顯示前導/摘錄 (類似於第一段或第二段) 。

這樣做最好的方法是什麼?有一個 the_content 濾波器,閱讀更多的自定義文字不會出現。你會推薦什麼

最佳解決思路

編輯

好的,有一個非常隱藏的本機功能,get_extended(),我從來不知道,並由 @kaiser 在 his answer 中大大解釋。我的答案只能是 @kaiser 的答案的擴充套件

原始答案

沒有本機功能來做到這一點。這裡最好的辦法是使用像 strpos 這樣的 PHP 函式來搜尋更多的標籤,然後根據結果做一些事情。

你可以嘗試這樣的東西

if( strpos( $post->post_content, '<!--more-->' ) ) {
    the_content( __( '&hellip; Read more about this article <span class="meta-nav">&rarr;</span>' ) );
}
else {
    the_excerpt();
}

次佳解決思路

當然,在核心的<!--more--> 標籤之前和之後都有一個 API 函式 (隱藏在核心的深度) 。由於完全為零的命名約定,WP 中的便捷部件通常被監視:get_extended()

// In the loop, after `the_post()` filled the global `$post`:
$info = get_extended( $post );

// The resulting data is an Array:
[Array] $info
    'main'      => the text before the `<!--more-->`
    'extended'  => the content after the `<!--more-->` comment
    'more_text' => the custom "Read More" text

結果將如下所示:

if ( have_posts() )
{
    while ( have_posts() )
    {
        the_post();

        $info = get_extended( $GLOBALS['post'] );

        if ( ! empty( $info['extended'] ) )
        {
            the_content( ! empty( $info['more_text'] ) ? $info['more_text'] : 'Read more' );
        }
        else
        {
            the_excerpt();
        }
    }
}

並根據<!--more--> 的存在切換摘錄和內容。請記住,預設情況下,WP 只接受沒有空格的<!--more--> 。因此,如果您的作者手工輸入並新增空格,<!-- more --> 將無法正常工作 (無論如何) 。

參考文獻

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