在一次開發中,我突然發現,the_excerpt函數無效了,不能顯示文章的摘要,我嘗試了多種可能的根源,仍然不解,為了不用query_posts就沒有問題,用query_posts之后就無效,為了解決這個問題,我翻閱了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());
- }
- /**
- * Retrieve the post excerpt.
- *
- * @since 0.71
- *
- * @param mixed $deprecated Not used.
- * @return string
- */
- function get_the_excerpt( $deprecated = '' ) {
- if ( !emptyempty( $deprecated ) )
- _deprecated_argument( __FUNCTION__, '2.3' );
- $post = get_post();
- if ( post_password_required() ) {
- return __( 'There is no excerpt because this is a protected post.' );
- }
- return apply_filters( 'get_the_excerpt', $post->post_excerpt );
- }
如果你仔細研究過,就會發現get_the_excerpt和the_excpert都是以抓取文章在數據庫中的post_excerpt字段來實現的,而當這個字段,也就是在后臺沒有填寫摘要時,為空,則會執行filter來調整和控制輸出的長度與內容.
如果你在開發中發現,怎么都不能讓the_excerpt顯示出原本的形式,你打算自己通過字符串截取等方法來代替這個函數的時候,不妨試試下面這段代碼:
- if(has_excerpt())the_excerpt();else{
- $length = apply_filters('excerpt_length',20);
- echo apply_filters('the_excerpt',wp_trim_words($post->post_content,$length));
- }
看上去極其簡單的幾行代碼,卻包含了很多我們以往沒有接觸過的知識,首先,apply_filters的運用很少有人做到嫻熟,例如我們希望讓文章按照WordPress的輸出格式輸出時,我們可以使用:
echo apply_filters('the_content','你的HTML代碼')
來代替,這一招幾乎被90%的開發者忽略,甚至很多人根本不知道這種用法.
其次,wp_trim_words是最長被忽視的函數,我們老是希望截取一段特定字符串長度的文字,結果根本不知道WordPress早就準備好了這樣的函數出來.
新聞熱點
疑難解答
圖片精選