-
-
Save searchwpgists/c88b753cee11f2b992e538688210a345 to your computer and use it in GitHub Desktop.
Add child PDF snippets to SearchWP result excerpt
This file contains 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 | |
// Add child PDF snippets to SearchWP result excerpt. | |
// @link https://searchwp.com/documentation/knowledge-base/append-pdf-content-to-search-result-excerpt/ | |
add_filter( 'get_the_excerpt', function( $excerpt ) { | |
global $post; | |
if ( ! $post instanceof WP_Post || ! is_search() || post_password_required() || $post->searchwp_excerpt_found ) { | |
return $excerpt; | |
} | |
$post->searchwp_excerpt_found = true; | |
$attached_pdfs = get_attached_media( 'application/pdf', $post->ID ); | |
if ( empty( $attached_pdfs ) ) { | |
return $excerpt; | |
} | |
// The number of words to include in PDF excerpt. | |
$pdf_excerpt_length = 20; | |
foreach ( $attached_pdfs as $attached_pdf ) { | |
$source = \SearchWP\Utils::get_post_type_source_name( 'attachment' ); | |
$pdf_entry = new \SearchWP\Entry( $source, $attached_pdf->ID, false, false ); | |
$pdf_excerpt = \SearchWP\Sources\Post::get_global_excerpt( | |
$pdf_entry, get_search_query(), $pdf_excerpt_length | |
); | |
if ( \SearchWP\Settings::get( 'highlighting', 'boolean' ) ) { | |
$pdf_excerpt = \SearchWP\Highlighter::apply( $pdf_excerpt, get_search_query() ); | |
} | |
if ( ! empty( $pdf_excerpt ) ) { | |
$pdf_label = get_the_title( $attached_pdf->ID ); | |
$excerpt .= '<br /><br /><strong>' . wp_kses_post( $pdf_label ) | |
. '</strong>: ' . wp_kses_post( $pdf_excerpt ); | |
} | |
} | |
return $excerpt; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment