Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use SearchWP to make WooCommerce Downloadable Product Document content searchable
<?php
// Tell SearchWP to parse WooCommerce Downloadable Product downloads for document content.
// The content will be extracted from downloadable documents where possible
// and stored as extra metadata with a key of `swp_wc_doc_content`
add_filter( 'searchwp_extra_metadata', function( $extra_metadata, $the_post ) {
if ( 'product' !== get_post_type( $the_post ) || ! class_exists( 'WC_Product' ) ) {
return $extra_metadata;
}
$product = new WC_Product( $the_post );
$downloads = $product->get_downloads();
if ( empty( $downloads ) ) {
return $extra_metadata;
}
// WooCommerce only stores a hashed ID, the filename, and the URL to the file
// but we need to retrieve the Media library ID for each downloadble file.
$upload_dir = wp_upload_dir();
foreach ( $downloads as $key => $download ) {
$relative_file_location = str_replace( trailingslashit( $upload_dir['baseurl'] ), '', $download['data']['file'] );
// We can use the relative file location to retrieve the post ID we need to parse the PDFs.
$file_id = get_posts( array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => array(
array(
'key' => '_wp_attached_file',
'value' => $relative_file_location,
),
),
) );
if ( empty( $file_id ) ) {
continue;
}
// Use SearchWP's parser to extract document content.
$parser = new SearchWPDocumentParser( $file_id[0] );
$product_content = ! empty( $parser->stored_content ) ? $parser->stored_content : $parser->extract_document_content();
// Store the extracted content as extra metadata.
$extra_metadata['swp_wc_doc_content'][] = $product_content;
}
return $extra_metadata;
}, 10, 2 );
// Add a Custom Field key for our WooCommerce Downloadable Product extracted Document Content.
add_filter( 'searchwp_custom_field_keys', function( $keys ) {
$keys[] = 'swp_wc_doc_content';
return $keys;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.