首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wordpress get_the_excerpt而不是$post->post_excerpt

Wordpress get_the_excerpt而不是$post->post_excerpt
EN

Stack Overflow用户
提问于 2018-11-03 11:28:02
回答 2查看 766关注 0票数 0

我正在尝试用get_the_excerpt替换下面函数中的$post->post_content,它只是动态地从the_content中推导出一段摘录。

原始函数:

代码语言:javascript
复制
function getExcerpt($post) {
    $summary = apply_filters('the_content', $post->post_content);
    return apply_filters("mc-message", $summary);
}

我本可以用$post->post_excerpt替换$post->post_content,但这不会返回任何内容,因为Wordpress编辑器的摘录元框中没有输入硬编码的摘录。阅读get_the_excerpt会从帖子内容中创建一个摘要。但是它没有传递任何值

代码语言:javascript
复制
function getExcerpt($post) {
    $deducted_excerpt = get_the_excerpt();
    $summary = apply_filters('the_content', $deducted_excerpt);
    return apply_filters("mc-message", $summary);
}
EN

回答 2

Stack Overflow用户

发布于 2018-11-03 19:04:02

是的,你是对的。当没有用户提供的摘录时,get_the_excerpt会生成完整帖子内容的按单词统计的精简版本。但是在这里,您没有在循环中使用get_the_excerpt。因此,您需要传递一个post对象或post ID作为参数来获取摘录。

来自codex:

如果在循环之外使用此函数,并且post没有自定义摘录,则此函数将使用wp_trim_excerpt()生成摘录。该函数使用get_the_content(),它必须与循环一起使用,如果在循环外部使用get_the_excerpt(),则会导致问题。为了避免这些问题,请在调用get_the_excerpt()之前使用setup_postdata()来设置全局$post对象。

你的代码应该是:

代码语言:javascript
复制
function getExcerpt($post) {
    $deducted_excerpt = get_the_excerpt($post);//<==== see here. $post object is passed as parameter.
    $summary = apply_filters('the_content', $deducted_excerpt);
    return apply_filters("mc-message", $summary);
}

More details on get_the_excerpt() function

票数 1
EN

Stack Overflow用户

发布于 2018-11-06 00:06:47

我最初将post id传递给它,但仍然没有返回我希望的截断内容摘录。因为Codex建议使用seup_postdata,所以我在我的函数前面加上了它。并解决了这个问题:

代码语言:javascript
复制
function getExcerpt($post) {
    setup_postdata($post);
    $deducted_excerpt = custom_excerpt($post);
    $summary = apply_filters('the_content', $deducted_excerpt);
    return apply_filters("mc-message", $summary);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53128146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档