Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top