Last active
February 9, 2021 20:24
-
-
Save jchristopher/31756254bfd9cd9c8eee2f7f5e734c76 to your computer and use it in GitHub Desktop.
Custom SearchWP Gutenberg Block Parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This wasn't working for me until I added
$blocks = parse_blocks( $content );
before the foreach