問題描述

我覺得我一定很想念一些很明顯的東西,但是我似乎無法讓 WordPress 合作。

我正在生成具有功能的 Facebook OG 標籤。一切都很好,除了摘錄。

由於 get_the_excerpt($post->ID)的棄用,是否有另一種建立摘錄的方式,而不必建立一個全新的迴圈?對我來說似乎過多了

我的第一本能是使用 apply_filters()

$description = apply_filters('the_excerpt', get_post($post->ID)->post_content);

這給我完整的帖子,完整的 HTML-formatted 內容。好的,一定是錯的所以我嘗試了下一個邏輯思路:

$description = apply_filters('get_the_excerpt', get_post($post->ID)->post_content);

沒有骰子。現在沒有 HTML,但它仍然是完整的帖子 (這真是令人困惑) 。

好的沒問題。讓我們跳過所有的花哨的東西,然後去修剪條目:

$description = wp_trim_excerpt(get_post($post->ID)->post_content);

不用找了。

所以,我的問題是這樣的:發生了什麼事?這裡有沒有什麼東西嗎?

我進入 WP 核心,找到 the_excerpt()的工作原理,看起來和我的電話是一樣的:

/**
 * Display the post excerpt.
 *
 * @since 0.71
 * @uses apply_filters() Calls 'the_excerpt' hook on post excerpt.
 */
function the_excerpt() {
    echo apply_filters('the_excerpt', get_the_excerpt());
}

根據我的發現我有幾個問題:

  1. 為什麼不按預期應用過濾器?

  2. 有沒有辦法在迴圈之外獲取摘錄而不建立新迴圈?

  3. 我瘋了嗎?

感謝提前看看。我在這裡很沮喪。

最佳解決方案

結果答案是在 wp_trim_excerpt()

它在 wp-includes/functions.php:1879 中定義:

/**
 * Generates an excerpt from the content, if needed.
 *
 * The excerpt word amount will be 55 words and if the amount is greater than
 * that, then the string ' [...]' will be appended to the excerpt. If the string
 * is less than 55 words, then the content will be returned as is.
 *
 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
 * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
 *
 * @since 1.5.0
 *
 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
 * @return string The excerpt.
 */
function wp_trim_excerpt($text = '') {
    $raw_excerpt = $text;
    if ( '' == $text ) {
        $text = get_the_content('');

        $text = strip_shortcodes( $text );

        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $excerpt_length = apply_filters('excerpt_length', 55);
        $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}

所以傳入的任何文字都不會被處理; 它只有在使用空引數呼叫時才起作用。

為瞭解決這個問題,我為我的主題新增了一個快速過濾器來解決問題:

/**
 * Allows for excerpt generation outside the loop.
 * 
 * @param string $text  The text to be trimmed
 * @return string       The trimmed text
 */
function rw_trim_excerpt( $text='' )
{
    $text = strip_shortcodes( $text );
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
    $excerpt_length = apply_filters('excerpt_length', 55);
    $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
    return wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
add_filter('wp_trim_excerpt', 'rw_trim_excerpt');

這有點多餘,但是我喜歡比每次想要生成摘錄時開啟新迴圈更好。

參考文獻

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