Getting posts excerpts outside the Loop in WordPress

The past three days I have been trying to get the excerpt of a post outside of the Loop with the following codes:

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

None of the above worked, I think its because I’m trying to get the excerpt outside of the loop. Some generated text that were on the page of the plugin, some broke my theme when put in different spots and some did absolutely nothing. I even googled methods of getting excerpts from outside of the loop, but for most of them you have to enter the the post_id for which you want the excerpt from.

Read More

Here is the full code that should output the exceprt. I listed the div “excerpt” for where I think the excerpt should go:

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

Again, I don’t really know where to turn to at this point so I came here. Is there anyone that could help me out to display the excerpt from each post with this plugin?

Related posts

Leave a Reply

2 comments

  1. You can get the unfiltered post excerpt by using $post->post_excerpt, assuming you have a post object. In your code above, you would want to call:

    $excerpt = apply_filters('get_the_excerpt', $single->post_excerpt);
    
  2. I am using the following function, it gets the post by $post_id, if it has excerpt set in admin it returns it, and if not, it uses WordPress function for generating it. I like it because this way the excerpt created respects your WP settings and will have same style as other excerpts created in the loop the standard way.

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