Created
September 10, 2020 17:05
-
-
Save jchristopher/d188b6243567ad3cc4e74d4852c82d01 to your computer and use it in GitHub Desktop.
Tell SearchWP to parse WooCommerce Downloadable Product downloads for document content
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 | |
// Tell SearchWP to parse WooCommerce Downloadable Product downloads for document content. | |
// The content will be extracted from downloadable documents where possible and stored | |
// in SearchWP's index as a Custom Field with a label of "SearchWP WooCommerce Download Content" | |
add_filter( 'searchwp\entry\data', function( $data, \SearchWP\Entry $entry ) { | |
if ( 'post.product' !== $entry->get_source()->get_name() || ! class_exists( 'WC_Product' ) ) { | |
return $data; | |
} | |
$product = new \WC_Product( $entry->get_id() ); | |
$downloads = $product->get_downloads(); | |
if ( empty( $downloads ) ) { | |
return $data; | |
} | |
// 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. | |
$download_content = []; | |
$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( [ | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'fields' => 'ids', | |
'meta_query' => [ [ | |
'key' => '_wp_attached_file', | |
'value' => $relative_file_location, | |
], ], | |
] ); | |
if ( ! empty( $file_id ) ) { | |
$download_content[] = \SearchWP\Document::get_content( get_post( $file_id[0] ) ); | |
} | |
} | |
$data['meta']['swp_wc_doc_content'] = \SearchWP\Utils::tokenize( $download_content ); | |
return $data; | |
}, 20, 2 ); | |
// Add "SearchWP WooCommerce Download Content" as available option. | |
add_filter( 'searchwp\source\attribute\options', function( $keys, $args ) { | |
if ( $args['attribute'] !== 'meta' ) { | |
return $keys; | |
} | |
$content_key = 'swp_wc_doc_content'; | |
if ( ! in_array( | |
$content_key, | |
array_map( function( $option ) { return $option->get_value(); }, $keys ) | |
) ) { | |
$keys[] = new \SearchWP\Option( $content_key, 'SearchWP WooCommerce Download Content' ); | |
} | |
return $keys; | |
}, 20, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment