在Wordpress中获取Loop外部的帖子摘录

时间:2012-11-04 22:10:13

标签: php wordpress

在过去的三天里,我一直试图通过以下代码获取圈外的帖子摘录:

1) <?php the_excerpt(); ?>
2) the_excerpt();
3) <?php get_the_excerpt(); ?>
4) get_the_excerpt();
5) '.apply_filters('the_excerpt',get_the_excerpt()).'

以上都没有,我认为是因为我试图在循环之外获取摘录。一些生成的文本出现在插件的页面上,有些文章在放入不同的地方时破坏了我的主题,而有些则完全没有。我甚至使用谷歌搜索从循环外部获取摘录的方法,但是对于大多数人来说,你必须输入你想要摘录的post_id

以下是应该输出exceprt的完整代码。我列出了div“摘录”,我认为摘录应该放在哪里:

private function cg_get_title($single) {
    global $cg_url;
    if($this->params['title']) {
        $title_array = get_post_meta($single->ID, $this->params['title']);
        $title = $title_array[0];
        if(!$title) {
            $title = $single->post_title;
        }
    }
    else {
        $title = $single->post_title;
    }
    $returnlink = ($this->params['lightbox']) ? ('"' . $cg_url . '/includes/CatGridPost.php?ID=' . $single->ID . '" class="cgpost"') : ('"' . get_permalink($single->ID)) . '"';
    $cgfontsize = $this->cg_get_font_size();
    $cgtitle = '<div class="cgback cgnojs ' . $this->params['showtitle'] . '"></div><div class="cgtitle cgnojs '
            . $this->params['showtitle'] . '"><p style="font-size:' . $cgfontsize . 'px;line-height:' . (1.2 * $cgfontsize) . 'px;">
            <a href=' . $returnlink . '>' . $title . '</a></p><DIV ID="EXCERPT">EXCERPT SHOULD GO HERE</DIV></div>';
    return $cgtitle;
}

同样,我真的不知道在这一点上转向何处,所以我来到这里。有没有人可以帮助我用这个插件显示每个帖子的摘录?

2 个答案:

答案 0 :(得分:4)

假设您有一个帖子对象,您可以使用$post->post_excerpt获取未经过滤的帖子摘录。在上面的代码中,您需要调用:

$excerpt = apply_filters('get_the_excerpt', $single->post_excerpt);

答案 1 :(得分:4)

我正在使用以下函数,它通过$ post_id获取帖子,如果它在admin中设置了摘录,则返回它,如果没有,则使用WordPress函数生成它。我喜欢它,因为这样创建的摘录会尊重您的WP设置,并且与标准方式在循环中创建的其他摘录具有相同的样式。

function my_excerpt($post_id) {
    $post = get_post($post_id);
    if ($post->post_excerpt) {
        // excerpt set, return it
        return apply_filters('the_excerpt', $the_post->post_excerpt);

    } else {
        setup_postdata( $post );
        $excerpt = get_the_excerpt();
        wp_reset_postdata();
        return $excerpt;
    }
}