【问题标题】:My custom get_the_excerpt() can't get excerpt by ID我的自定义 get_the_excerpt() 无法通过 ID 获取摘录
【发布时间】: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)."&#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;
}

还是没有变化。

【问题讨论】:

  • echo excerpt('30', $previous -&gt; ID); 中的“->”周围有空格是错字吗?我很确定这不会起作用-我怀疑这会使 $post_id 在您的自定义调用中未定义-所以它都使用当前的 $post。另外,我很确定您不必费心get_post - 只需将您的 post_id 传递给 get_the_excerpt 就可以了。
  • 没有变化,周围没有空格“->”你是对的,我可以通过 $post_id 但这也不会改变问题。 :(

标签: php wordpress function


【解决方案1】:

添加 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;
}

【讨论】:

    【解决方案2】:

    以下函数获取两个参数: - $num : 你要显示的字符数 - $post_id:你要获取内容的帖子的ID

    和: - 如果内容中有标记,则返回文本,直到它 - 如果 $num 为 = 0,则返回内容直到第一个句号 否则返回在 $num 上指定的字符数,在字符串末尾添加“...”

    function my_custom_excerpt($num = 0,$post_id=''){
    $post=get_post($post_id);
    $content=$post->post_content;
    if(strpos($content,'&lt;!&#8211;more&#8211;&gt;')>0){
        return substr($content,0,strpos($content,'&lt;!&#8211;more&#8211;&gt;'));
    }else{
        if($num===0){
            return substr($content,0,strpos($content,'.')+1);
        }else{
            return substr($content,0,$num).((strlen($content)>$num)?"...":"");
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      相关资源
      最近更新 更多