Posted on

ACF: Indexing files from File fields

Relevanssi can index attachment contents from files linked to posts with ACF File fields. This does not happen automatically but requires some extra code.

The code required depends on which return value you use for your ACF File fields. If you use “File ID”, the code looks like this:

add_filter( 'relevanssi_content_to_index', 'rlv_get_acf_file', 10, 2 );
add_filter( 'relevanssi_excerpt_content', 'rlv_get_acf_file', 10, 2 );

function rlv_get_acf_file( $content, $_post ) {
    $file = get_field( 'pdf_file', $_post->ID );
    if ( ! empty( $file ) ) {
        $content .= ' ' . get_post_meta( $file, '_relevanssi_pdf_content', true );
    }
    return $content;
}

For “File Array”, the code looks like this:

add_filter( 'relevanssi_content_to_index', 'rlv_get_acf_file', 10, 2 );
add_filter( 'relevanssi_excerpt_content', 'rlv_get_acf_file', 10, 2 );

function rlv_get_acf_file( $content, $_post ) {
    $file = get_field( 'pdf_file', $_post->ID );
    if ( is_array( $file ) && isset( $file['ID'] ) ) {
        $content .= ' ' . get_post_meta( $file['ID'], '_relevanssi_pdf_content', true );
    }
    return $content;
}

“File URL” is the most complex case, and as it requires extra database queries, I would strongly recommend against using it. The code looks like this:

add_filter( 'relevanssi_content_to_index', 'rlv_get_acf_file', 10, 2 );
add_filter( 'relevanssi_excerpt_content', 'rlv_get_acf_file', 10, 2 );

function rlv_get_acf_file( $content, $_post ) {
    $file = get_field( 'pdf_file', $_post->ID );
    if ( ! empty( $file ) ) {
        $upload_dir = wp_upload_dir();
        $file       = str_replace( $upload_dir['baseurl'] . '/', '', $file );

        global $wpdb;
        $file_id = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
                $file
            )
        );
        $content .= ' ' . get_post_meta( $file_id, '_relevanssi_pdf_content', true );
    }
    return $content;
}

Add the code to your site and rebuild the index. If you have read the attachment contents, Relevanssi will now include it in the posts to which the files are linked. Relevanssi will also use the attachment content for building excerpts.

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 *