Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

Indexing HTML comments
By default, Relevanssi does not index HTML comments inside your posts. Relevanssi removes all HTML tags before indexing, and HTML…

Related Posts:

Comment Section:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed