問題描述
我有一個程式碼呼叫 get_the_title()它可以工作,但 get_the_excerpt()返回空。我該如何讓它工作?
此程式碼位於稱為 「WP Facebook Open Graph 協議」 的外掛中。這是我想改變的部分:
if (is_singular('post')) {
if (has_excerpt($post->ID)) {
echo "t<meta property='og:description' content='".esc_attr(strip_tags(get_the_excerpt($post->ID)))."' />n";
}else{
echo "t<meta property='og:description' content='". [?] ."' />n";
}
}else{
echo "t<meta property='og:description' content='".get_bloginfo('description')."' />n";
}
在這裡,has_excerpt 總是失敗,get_the_excerpt($post->ID)不再工作了 (已棄用) 。
那麼,我該如何在那裡顯示摘錄?
ps:我也在使用”Advanced Excerpt” 外掛
最佳解決方案
在沒有帖子物件的情況下檢視如何執行此操作時,我發現這個問題。
我的另外一項研究發現了這種光滑的技術:
$text = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
次佳解決方案
嘗試這個:
在 functions.php 中建立一個新的函式,然後從中呼叫它。
function get_excerpt_by_id($post_id){
$the_post = get_post($post_id); //Gets post ID
$the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
$excerpt_length = 35; //Sets excerpt length by word count
$the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, '…');
$the_excerpt = implode(' ', $words);
endif;
$the_excerpt = '<p>' . $the_excerpt . '</p>';
return $the_excerpt;
}
Here’s a post describing the code.
第三種解決方案
既然看起來你已經有了 post 物件,你需要摘錄,你可以強制要做的事情:
setup_postdata( $post );
$excerpt = get_the_excerpt();
setup_postdata()功能將全域性化 $post 物件,使其可用於常規舊迴圈功能。當你在迴圈裡面時,你呼叫 the_post(),它會為你設定的東西在你需要手動強制的迴圈之外。
第四種方案
現在您可以簡單地使用 get_the_excerpt( $postID )功能。既然:WordPress 4.5.0 引入了 $post 引數。
第五種方案
使用 my_excerpt($post->post_content, get_the_excerpt())並使用 Using wp_trim_excerpt to get the_excerpt() outside the loop 的 my_excerpt()功能
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。