在我的 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;
}
仍然没有变化。
最佳答案
加入setup_postdata($post);解决了我的问题。
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
setup_postdata($post);
$output = get_the_excerpt($post);
wp_reset_postdata();
$post = $save_post;
return $output;
}
关于php - 我的自定义 get_the_excerpt() 无法通过 ID 获取摘录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42401823/