[英]Loop posts excerpt returns empty
我以這種方式顯示我的帖子列表:
[-- IMAGE --]
[-- Title --]
[-- Excerpt --]
[-- "Read more" --]
當我在index.php
文件中使用它時,我的代碼工作正常,例如:
while(have_posts())
{
the_post();
$link = get_permalink();
$title = the_title();
$excerpt = the_excerpt();
}
然后在functions.php
中,將篩選器應用於摘要:
add_filter('excerpt_length', 'custom_excerpt_length');
add_filter('excerpt_more', 'new_excerpt_more');
function custom_excerpt_length()
{
return 14;
}
function new_excerpt_more($more)
{
global $post;
return '... <a href="'. get_permalink($post->ID) . '">Read more</a>';
}
但是,現在我必須遍歷functions.php
內的帖子,並且已經找到了標題和鏈接,但沒有摘錄。
$posts = get_posts($args);
foreach($posts as $post)
{
$link = get_permalink($post);
$title = get_the_title($post);
$excerpt = get_the_excerpt($post); // Returns empty and I'd like to apply the filters
}
如何將過濾器應用於函數get_the_excerpt
,為什么它為空?
從文檔中 :
如果在The Loop之外使用此函數,並且帖子沒有自定義摘錄,則此函數將使用wp_trim_excerpt()生成摘錄。 該函數使用get_the_content() ,該函數必須與The Loop一起使用,如果在Loop之外使用get_the_excerpt() ,則會導致問題。 為了避免這些問題,使用setup_postdata()之前調用get_the_excerpt()建立全球$ post對象。
這應該工作:
$posts = get_posts($args);
foreach($posts as $post)
{
setup_postdata($post);
$link = get_permalink($post);
$title = get_the_title($post);
$excerpt = get_the_excerpt($post);
}
wp_reset_postdata();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.