問題描述

有沒有辦法將 the_excerpt() 與 the_content() 進行比較,以確定是否顯示 the_excerpt() 的整個帖子內容?例如,如果一個職位特別短。

最終我想在截圖的末尾有一個”Read more” 連結。但是我想讓它說 1 個帖子,另一個是影片格式的帖子 (即…「觀看影片」,而不是 「閱讀其餘」) 。但同時我也不想在摘錄之後手動打這個,但是我有足夠的帖子足夠短,不需要’read more’ 連結,因為 the_excerpt 顯示完整的帖子。

但是新增固定連結到 excerpt_more 過濾器是不正確的,因為它不會新增到沒有其他內容的影片帖子的連結。

所以我被困在兩者之間。我希望是有道理的。如果沒有’t it’s 晚了,我會盡量在早上去 re-explain 。

最佳解決方案

您正在嘗試的影片正是為了處理 Post Formats 而設計的。

將其新增到函式中:

add_theme_support( 'post-formats', array( 'video' ) );

然後這個來處理你的閱讀更多連結:

if( !has_post_format( 'video' ) ) {
    echo '<a href="http://'%20.%20get_permalink()%20.%20'">Read More&hellip;</a>';
} else {
    echo '<a href="http://'%20.%20get_permalink()%20.%20'">Watch the Video&hellip;</a>';
}

次佳解決方案

@mrwweb 是對的,post 格式在大多數情況下非常有用。

作為一個更通用的解決方案,您可以將 the_excerpt()the_content()組合在一起:

function wpse_51699_conditional_excerpt( $more_link_text = null, $stripteaser = false )
{
    $excerpt = apply_filters( 'the_excerpt', get_the_excerpt() );

    $content = get_the_content( $more_link_text, $stripteaser );
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]&gt;', $content);

    $stripped_content = strip_tags( $content );
    $content_length   = mb_strlen( $stripped_content, 'utf-8' );
    $excerpt_length   = mb_strlen( $excerpt, 'utf-8' );

    // $content is just 20% longer than excerpt. Adjust this to your needs.
    if ( ( $excerpt_length * 1.2 ) >= $content_length )
    {
        print $content;
        return;
    }
    echo $excerpt . $more_link_text;
}

在你的主題你現在打電話

wpse_51699_conditional_excerpt( sprintf( '<a href="%1$s">Read more</a>', get_permalink() ) );

… 而不是 the_excerpt();

參考文獻

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