0

The problem I have is im not getting the automatic excerpt (the_excerpt()) when I create a post with gutenberg blocks, If I put an image or something before the text it looks like gutenberg does not undestand it, if I put just text is ok but If I add images or a different block that is not text it is empty, is there a way to detect the first block of text in a post and use it like excerpt.

Thank you.

0

You can hook the get_the_excerpt filter with parse_blocks to extract the content of your post.

add_filter( 'get_the_excerpt', 'se378694_default_excerpt', 10, 2 );

function se378694_default_excerpt( string $post_excerpt, WP_Post $post ):string {
    if ( empty( $post_excerpt ) ) {
        $blocks = parse_blocks( $post->post_content );

        // check if the first block matches the type of content you want for your excerpt
        if ( ... ) {
            $post_excerpt = render_block( $blocks[ 0 ] );
        }
    }
}

You can use render_block() if you want to get the final content of any block in your post content.

And parse_blocks() to convert the post content (string) into an array of blocks.

3
  • 1
    Thanks for your asnwer Tim but Im a little bit confused what can I put in the if statement to display text? them I have to call get_the_excerpt(); where I want to display the excerpt? Thank you Nov 23 '20 at 21:47
  • get_the_ecxerpt() or the_excerpt() are the standard methods to get or print the excerpt in your template.
    – Tim
    Nov 24 '20 at 8:04
  • The code provided will add a hook everytime someone try to get or print the excerpt. You can try to var_dump the $blocks variable to see what is inside. There is a property that will tell you the block name (core/paragraph) for example. Of it is a paragraph, then try to render it and return the value to generate your excerpt.
    – Tim
    Nov 24 '20 at 8:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.