Olen
Olen

Reputation: 1185

Excerpt outside loop

Trying to get excerpt outside loop, but turns out it's not that simple as first thought. The excerpt should echo the text before the more tag. Meaning I have not set a specific maximum amount of letters the excerpt should include. This is because I don't want the sentences to stop in the middle of them.

I have set the post id to the following:

<?php $post_id = 27; ?>

Then, I have tried adding different functions. These are both found on StackOverflow and Google. But for some reason I can't get them to work. I suspect some of them are old and that WordPress has changed since then.

First try:

function get_excerpt_by_id( $post_id = 27 ) {
    global $post;
    $save_post = $post;
    $post = get_post( $post_id );
    setup_postdata( $post );
    $excerpt = get_the_excerpt();
    $post = $save_post;
    wp_reset_postdata( $post );
    return $excerpt;
}

Second try:

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

Any ideas how this should be solved?

Edit:

<?php $post_id = 27; // Endre denne ?>
            <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id("$post_id"), full); ?>

            <div style="background-image:url('<?php echo $image[0]; ?>')">
                <div class="col-md-6">
                    <h1><?php echo get_the_title("$post_id");?></h1>
                    <div>
                    <?php get_post_field( 'post_excerpt', $post_id ); ?>
                    <?php $excerpt = get_the_excerpt( $post_id ) ?> 
                    <?php echo $excerpt; ?>
                    </div>
                    <div>
                        <a href="<?php echo get_permalink("$post_id");?>" rel="" id="trykklink" class="btn btn-outline-fill-white littluft nomarginleft" role="button" title="" onmouseover="this.title='';">Read more</a>
                    </div>
                </div>   
                <div class="col-md-6">
                </div>
            </div>

Upvotes: 0

Views: 560

Answers (2)

Adrian Lambertz
Adrian Lambertz

Reputation: 923

<?php $excerpt = get_the_excerpt( $post ) ?> 

$post can be the post id or the $post object.

From WP Codex

Upvotes: 0

m1tk00
m1tk00

Reputation: 124

You can try the following

<?php get_post_field( 'post_excerpt', $post_id ); ?>

for more information please check here

Upvotes: 1

Related Questions