Post excerpt doesnt work

Hello stackoverflow people, I need help. I’m using wordpress and somehow I can’t use this function:

$post_id = 12;
    echo get_post($post_id)->post_excerpt;

Somehow it prints nothing. Here is the full div. Can you help me to solve this problem?

                <div id="block1">
                    <div class="inblock1">
                        <h2>About boots</h2>
                        <p><?php $post_id = 12;
echo get_post($post_id)->post_excerpt; ?> </p>
                        <a href="/about-boots/" class="rodykle">apac</a>
                    </div>
                </div>

Related posts

2 comments

  1. It sounds like you don’t actually have an excerpt set for this post. You can always use a conditional to test it, and output a custom excerpt (from the post_content) if one doesn’t exist:

    $my_post = get_post($post_id);
    // If the excerpt is empty, generate one from post_content, else display the saved excerpt
    echo empty($my_post->post_excerpt) ? wp_trim_words($my_post->post_content, 55, '...') : $my_post->post_excerpt;
    

    Read more about wp_trim_words() in the Codex.

  2. You may need to use setup_postdata() because <?php $post_id = 12; echo get_post($post_id)->post_excerpt; ?> will return excerpt if you have excerpt data in excerpt field but below code will return data from content if you don’t have data in excerpt field.

    $post_id = 12;
    $tempVar = $post;
    $post = get_post($post_id);
    setup_postdata($post);
    
    the_excerpt();
    
    wp_reset_postdata();
    $post = $tempVar;
    

Comments are closed.