我正在尝试用get_the_excerpt替换下面函数中的$post->post_content,它只是动态地从the_content中推导出一段摘录。
原始函数:
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会从帖子内容中创建一个摘要。但是它没有传递任何值
function getExcerpt($post) {
$deducted_excerpt = get_the_excerpt();
$summary = apply_filters('the_content', $deducted_excerpt);
return apply_filters("mc-message", $summary);
}发布于 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对象。
你的代码应该是:
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);
}发布于 2018-11-06 00:06:47
我最初将post id传递给它,但仍然没有返回我希望的截断内容摘录。因为Codex建议使用seup_postdata,所以我在我的函数前面加上了它。并解决了这个问题:
function getExcerpt($post) {
setup_postdata($post);
$deducted_excerpt = custom_excerpt($post);
$summary = apply_filters('the_content', $deducted_excerpt);
return apply_filters("mc-message", $summary);
}https://stackoverflow.com/questions/53128146
复制相似问题