Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom SearchWP Gutenberg Block Parser
<?php
// Disable automatic block parsing during SearchWP index.
add_filter( 'searchwp\source\post\attributes\content\do_blocks', '__return_false' );
// SearchWP custom Block parser.
add_filter( 'searchwp\source\post\attributes\content', function( $content, $args ) {
if ( 'post' === $args['post']->post_type ) {
// This will hold the content we want to index for this Post.
$content_to_index = '';
// These are the only Gutenberg Blocks we want to index.
$blocks_to_index = [
'core/heading',
'core/paragraph',
'core/list',
'core/quote',
'core/table',
];
// Loop over the Blocks of this Post and render the content
// for the Blocks we want, skip the Blocks we don't.
$blocks = parse_blocks( $content );
foreach ( $blocks as $block ) {
if ( in_array( $block['blockName'], $blocks_to_index, true ) ) {
$content_to_index .= render_block( $block );
}
}
// Replace the incoming $content with the rendered Block content.
$content = $content_to_index;
}
return $content;
}, 10, 2 );
@noahck
Copy link

noahck commented Feb 9, 2021

This wasn't working for me until I added $blocks = parse_blocks( $content ); before the foreach

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment