php - 我的自定义 get_the_excerpt() 无法通过 ID 获取摘录

标签 php wordpress function

在我的 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)."&#8230";
    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)."&#8230";
    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/

相关文章:

javascript - jQuery - 重定向到页面后更改页面的属性

function - (gcloud.functions.deploy) 使用特定服务帐户部署功能时权限被拒绝

php - 在 PHP(或 Perl)中按国家/地区格式化送货地址

PHP:从 jQuery 解析 JSON

php - 创建一个随机的 Magento 优惠券

php - 如何使用 Wordpress Rest Api 获取当前登录用户?

php - 减少 WP_List_Table 的表格宽度

Javascript变量复制范围

PHP:收集传递给函数的所有变量作为数组?

php - 使用php中的编辑和删除图像删除和更新行