【发布时间】:2017-07-13 02:41:45
【问题描述】:
在我的 single.php 页面上,我正在尝试创建一个函数,按 ID 为我提供特定帖子的自定义长度摘录。
以下是我正在运行的两个函数。
/* Custom get_the_excerpt to allow getting Post excerpt by ID */
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
$output = get_the_excerpt($post);
$post = $save_post;
return $output;
}
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', custom_get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
我用什么来调用函数。
<?php $previous = get_previous_post();
echo excerpt('30', $previous -> ID); ?>
我遇到的问题是 $post 给了我以前的帖子信息,但是当我将它传递给 get_the_excerpt 时,它会返回当前的帖子摘录而不是以前的帖子摘录。
编辑
在几个人告诉我我可以将 $post_id 传递给 get_the_excerpt() 之后,将函数更改为此
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
还是没有变化。
【问题讨论】:
-
echo excerpt('30', $previous -> ID);中的“->”周围有空格是错字吗?我很确定这不会起作用-我怀疑这会使 $post_id 在您的自定义调用中未定义-所以它都使用当前的 $post。另外,我很确定您不必费心get_post- 只需将您的 post_id 传递给 get_the_excerpt 就可以了。 -
没有变化,周围没有空格“->”你是对的,我可以通过 $post_id 但这也不会改变问题。 :(