Using WordPress ‘excerpt_remove_blocks()’ PHP function

The excerpt_remove_blocks() WordPress PHP function is used to parse blocks out of a content string, specifically rendering those blocks most suitable for an excerpt. The aim is to extract a succinct piece of text that is relevant to the overall post content.

Usage

Here’s a basic example of how to use the excerpt_remove_blocks() function:

$post_content = "This is my blog post content with various blocks.";
$excerpt_content = excerpt_remove_blocks($post_content);
echo $excerpt_content;

In this example, the excerpt_remove_blocks() function is called with $post_content as its argument, and it returns the parsed content suitable for an excerpt, stored in $excerpt_content.

Parameters

  • $content (string) – Required. This is the content that is to be parsed to create the excerpt.

More information

See WordPress Developer Resources: excerpt_remove_blocks()
It’s important to keep in mind that this function is part of the block editor functions in WordPress.

Examples

Basic Usage

This example simply parses content and outputs the excerpt:

$post_content = "This is a post with multiple blocks.";
$excerpt = excerpt_remove_blocks($post_content);
echo $excerpt;

This code takes $post_content, runs it through the excerpt_remove_blocks() function to generate an excerpt, then outputs it.

Adding the Excerpt to a Post

This example uses the function in the context of creating a post:

$post_content = "This is a post with multiple blocks.";
$excerpt = excerpt_remove_blocks($post_content);

$post_data = array(
  'post_excerpt'  => $excerpt,
  'post_content'  => $post_content,
);
wp_insert_post($post_data);

This example generates an excerpt from $post_content, then includes it in the array used to create a new post.

Updating the Excerpt of an Existing Post

$post = get_post(123); // get a specific post by ID
$excerpt = excerpt_remove_blocks($post->post_content);

$post_data = array(
  'ID'            => $post->ID,
  'post_excerpt'  => $excerpt,
);
wp_update_post($post_data);

This example retrieves a post, generates an excerpt from its content, then updates the post’s excerpt field with the new excerpt.

Displaying the Excerpt on a Page

$post = get_post(123);
$excerpt = excerpt_remove_blocks($post->post_content);
echo '<p>' . $excerpt . '</p>';

This code retrieves a post, creates an excerpt from its content, and then displays it on the page.

Using the Function with a Custom Block of Content

$custom_content = "This is my custom content block.";
$excerpt = excerpt_remove_blocks($custom_content);
echo $excerpt;

This example shows that the function can also be used with a custom content block, not just with post content. It generates an excerpt from the $custom_content and outputs it.