Posted on

Indexing attachments from File blocks

The Relevanssi attachment indexing assumes the files are connected to the posts using the WordPress attachment mechanism. What if you don’t use that but instead add the files to the pages using the File block in the block editor?

That’s not a problem, but it requires some extra code. Add this function to your site to index the contents of files added with the File block:

add_filter( 'relevanssi_block_to_render', function( $block ) {
    if ( 'core/file' === $block['blockName'] ) {
        $file_id      = $block['attrs']['id'];
        $file_content = get_post_meta( $file_id, '_relevanssi_pdf_content', true );
        if ( $file_content ) {
            $block['innerContent'][0] = $file_content;
        }
    }
    return $block;
} );

This function uses the relevanssi_block_to_render filter hook. Whenever a core/file block is encountered, the function fetches the file contents from the _relevanssi_pdf_content custom field for the attachment post and replaces the block contents with that.

This works great for indexing but does not include the file contents in excerpts. That requires another function:

add_filter( 'relevanssi_pre_excerpt_content', function( $content, $post) {
    $m = preg_match( '/<!-- wp:file.*?"id":(\d+).*?<!-- \/wp:file -->/s', $content, $matches );
    if ( $m > 0 ) {
        $file_id = $matches[1];
        $file_content = get_post_meta( $file_id, '_relevanssi_pdf_content', true );
        if ( $file_content ) {
            $content = preg_replace( '#' . preg_quote( $matches[0], '#' ) . '#', $file_content, $content );
        }
    }
    return $content;
}, 10, 2 );

This filter uses relevanssi_pre_excerpt_content and replaces the file block comment in the post content with the file contents from the custom field.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *