Last active
July 2, 2020 16:50
-
-
Save jchristopher/8a39415524c25bf965304fa20b2760b2 to your computer and use it in GitHub Desktop.
Append attached PDF content to 'parent' post during indexing in SearchWP
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 | |
// @link https://searchwp.com/documentation/knowledge-base/append-document-content-to-parent-post-content/ | |
// Retrieve child PDF content and add as 'extra' data to a SearchWP Entry. | |
add_filter( 'searchwp\entry\data', function( $data, \SearchWP\Entry $entry ) { | |
// Convert the SearchWP Entry into it's native object type. | |
$entry = $entry->native(); | |
// We only want to consider WP_Post objects. | |
if ( ! $entry instanceof \WP_Post ) { | |
return $data; | |
} | |
// Retrieve PDFs that have been uploaded to this Entry. | |
$pdfs = get_posts( [ | |
'post_type' => 'attachment', | |
'post_mime_type' => 'application/pdf', | |
'post_status' => 'inherit', | |
'nopaging' => true, | |
'post_parent' => $entry->ID, | |
] ); | |
if ( empty( $pdfs ) ) { | |
return $data; | |
} | |
// Retrieve PDF content for PDFs and store as extra data. | |
$data['meta'][ 'searchwp_child_pdf_content' ] = array_map( function( $pdf ) { | |
return \SearchWP\Document::get_content( $pdf ); | |
}, $pdfs ); | |
return $data; | |
}, 20, 2 ); | |
// Add "Attached PDF Content" as available option to SearchWP Source Attributes. | |
add_filter( 'searchwp\source\attribute\options', function( $keys, $args ) { | |
if ( $args['attribute'] !== 'meta' ) { | |
return $keys; | |
} | |
// This key is the same as the one used in the searchwp\entry\data hook above, they must be the same. | |
$pdf_content_key = 'searchwp_child_pdf_content'; | |
// Add "Attached PDF Content" Option if it does not exist already. | |
if ( ! in_array( | |
$pdf_content_key, | |
array_map( function( $option ) { return $option->get_value(); }, $keys ) | |
) ) { | |
$keys[] = new \SearchWP\Option( $pdf_content_key, 'Attached PDF Content' ); | |
} | |
return $keys; | |
}, 20, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment