<?php
add_filter( 'get_the_excerpt', function( $excerpt ) {
global $post;
$pdf_excerpt_length = 15;
if ( ! post_password_required() ) {
$common_words = array();
if ( class_exists( 'SearchWP' ) ) {
$searchwp = SearchWP::instance();
$common_words = $searchwp->common;
}
if ( isset( FWP()->facet->facets['keywords'] ) ) {
$terms = FWP()->facet->facets['keywords']['selected_values'];
$terms = (array) $terms;
} else {
$terms = explode( ' ', get_search_query() );
$terms = array_map( 'sanitize_text_field', $terms );
}
$attached_pdfs = get_attached_media( 'application/pdf', $post->ID );
foreach ( $attached_pdfs as $attached_pdf ) {
if ( $pdf_content = get_post_meta( $attached_pdf->ID, 'searchwp_content', true ) ) {
$flag = false;
foreach ( $terms as $termkey => $term ) {
if ( ! in_array( $term, $common_words ) && absint( apply_filters( 'searchwp_minimum_word_length', 3 ) ) <= strlen( $term ) ) {
$flag = $term;
break;
}
}
$haystack = explode( ' ', $pdf_content );
$pdf_excerpt = '';
foreach ( $haystack as $haystack_key => $haystack_term ) {
preg_match( "/b$flagb(?!([^<]+)?>)/i", $haystack_term, $matches );
if ( count( $matches ) ) {
$buffer = floor( ( $pdf_excerpt_length - 1 ) / 3 );
$start = 0;
$underflow = 0;
if ( $haystack_key < $buffer ) {
$underflow = $buffer - $haystack_key;
} else {
$start = $haystack_key - $buffer;
}
$end = count( $haystack );
if ( $end > ( $haystack_key + ( $buffer * 2 ) ) ) {
$end = $haystack_key + ( $buffer * 2 );
}
$end += $underflow;
$pdf_excerpt = array_slice( $haystack, $start, $end - $start );
$pdf_excerpt = implode( ' ', $pdf_excerpt );
break;
}
}
if ( ! empty( $pdf_excerpt ) ) {
$pdf_label = get_the_title( $attached_pdf->ID );
$excerpt .= '<br /><br /><strong>' . $pdf_label . '</strong>: ' . $pdf_excerpt;
}
}
}
}
return $excerpt;
});