Home › Forums › Product Support Forums › Ajax Search Pro for WordPress Support › Multiple questions ( CPT , size title ; stats ) › Reply To: Multiple questions ( CPT , size title ; stats )
March 24, 2022 at 2:38 pm
#37303
Keymaster
Well, context word finding is a bit more complicated than this, I can try to copy paste the same function we use in the core, but this may not work at all:
function x_context_find($str, $needle, $context, $maxlength, $str_length_limit = 10000, $false_on_no_match = false) {
$haystack = remove_accents(' '.trim($str).' ');
$haystack = wd_substr_at_word(ASP_mb::strtolower($haystack), $str_length_limit, '');
$needle = remove_accents(ASP_mb::strtolower($needle));
if ( $needle == "" ) {
if ( ASP_mb::strlen($str) > $maxlength) {
return wd_substr_at_word($str, $maxlength);
} else {
return $str;
}
}
$chrArray = preg_split('//u', $haystack, -1, PREG_SPLIT_NO_EMPTY);
$hay_length = count($chrArray) - 1;
if ( $i = ASP_mb::strpos($haystack, $needle) ) {
$start=$i;
$end=$i;
$spaces=0;
while ($spaces < ((int) $context/2) && $start > 0) {
$start--;
if ($chrArray[$start] == ' ') {
$spaces++;
}
}
while ($spaces < ($context +1) && $end < $hay_length) {
$end++;
if ($chrArray[$end] == ' ') {
$spaces++;
}
}
while ($spaces < ($context +1) && $start > 0) {
$start--;
if ($chrArray[$start] == ' ') {
$spaces++;
}
}
$str_start = ($start - 1) < 0 ? 0 : ($start -1);
$str_end = ($end - 1) < 0 ? 0 : ($end -1);
$result = trim( ASP_mb::substr($str, $str_start, ($str_end - $str_start)) );
// Somewhere inbetween..
if ( $start != 0 && $end < $hay_length )
return "... " . $result . " ...";
// Beginning
if ( $start == 0 && $end < $hay_length )
return $result . " ...";
// End
if ( $start != 0 && $end == $hay_length )
return "... " . $result;
// If it is too long, strip it
if ( ASP_mb::strlen($result) > $maxlength)
return wd_substr_at_word( $result, $maxlength );
// Else, it is the whole
return $result;
} else {
if ( $false_on_no_match )
return false;
// If it is too long, strip it
if ( ASP_mb::strlen($str) > $maxlength)
return wd_substr_at_word( $str, $maxlength );
return $str;
}
}
function asp_context_find( $results, $search_id, $is_ajax, $args ) {
foreach ($results as $k=>&$r) {
$r->content = x_context_find($r->content, $args['s'], floor(ASP_mb::strlen($r->content) / 6), 130);
}
return $results;
}
add_filter( 'asp_results', 'asp_context_find', 10, 4 );