How to add excerpt for WordPress Post blocks

Share Now

<?php
if ( has_excerpt() ) {
    $output = get_the_excerpt();
} else {
    // Get and render content, including block content
    $raw_content = apply_filters( 'the_content', get_the_content() );

    // Strip ALL HTML tags
    $plain_text = wp_strip_all_tags( $raw_content );

    // Trim to 30 words
    $word_limit = 30;
    $words = preg_split( '/\s+/', $plain_text, -1, PREG_SPLIT_NO_EMPTY );

    if ( count( $words ) > $word_limit ) {
        $output = implode( ' ', array_slice( $words, 0, $word_limit ) ) . ' […]';
    } else {
        $output = implode( ' ', $words );
    }
}
?>

<p class="mt-4 text-gray-700 font-poppins leading-[30px] font-lexend">
  <?php echo esc_html( $output ); ?>
</p>

Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert