Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active February 9, 2021 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/31756254bfd9cd9c8eee2f7f5e734c76 to your computer and use it in GitHub Desktop.
Save jchristopher/31756254bfd9cd9c8eee2f7f5e734c76 to your computer and use it in GitHub Desktop.
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