1

im doing a custom search result page with function that extract from the_content() some words before and after the search query. (Eg ?s=cool result=[...sterday was cool and the par...]

It's working but i only get the extract for the last item found in the content.

how to find position for each item found ? i know the logic but not how to properly code it and dont want to use any plugin like revelanssi.

what is the best way ?

my code functions.php

function show_search_blog(){
    $title = get_the_title();
    // change case for better results
    $mystring = strtolower($title);
    $findme   = get_search_query();
    $pos = strpos($mystring, $findme);
    // vars
    $newContent = $exctractBeforeQuery = $exctractAfterQuery = '';
    //
    if ($pos === false) {
        $link = get_the_permalink();
        $newContent .= "<a href='".$link."'>".$title."</a> ";
        // search without tags
        $content = wp_strip_all_tags(get_the_content());

        $pos = strpos($content, $findme);
        // $pos return only value for the last found
        // place for the loop for each keyword found
        if($pos==''){
        $newContent .= "(Debug : keyword found in tags (like in href link attr)<br>";
        //ignore search query in tags
            }
        else{
            $newContent .= "(Debug : Position".$pos.") - ";
            $exctractAfterQuery = substr($content,($pos+strlen($findme) ),40);
            $exctractBeforeQuery = substr($content,$pos-40,40);
            $newContent .= "[...".$exctractBeforeQuery.'<strong class="search-highlight">'.$findme."</strong>".$exctractAfterQuery."...]<br>";
            }
        } 
    else{
    $keys = implode('|', explode(' ', get_search_query()));
    $title = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $title);
        $link = get_the_permalink();
        $newContent .= "<a href='".$link."'>".$title."</a><br>";
    }
  return $newContent;   
}  

index.php

if(is_search()){
    // check for keyword
    if($_GET['s'] == ''){echo 'no keyword - add form again';}
    else{ 
    // add style for the highlight  
    echo "<style>.search-highlight{background:yellow;}</style>";
    // sanitize
    $s = filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING);
    echo "Search for: ".$s."<br>";
    // reset vars
    $html = $pluriel = $nbrResult = ""; 
    // args 
    $args = array(
        'posts_per_page' => -1,
        'orderby' => 'date',
        'post_type' => 'post',
        's' => $s
    );
    // query and loop
  $q = new WP_Query($args);

  if($q->have_posts()){
        while($q->have_posts()){
            $q->the_post();
            $html .= show_search_blog(); // call my function
            }
        $nbrResult = $q->found_posts;
        if($nbrResult>1){$pluriel="s";}
        echo $nbrResult." Result".$pluriel." in the Blog : <br>".$html."<br>";
        wp_reset_postdata();
        }
    else{
        echo "Sorry... nothing found";
        }                                                                                                                                                                                                                                                                                       
    }
}
2
  • May be easier to install and configure Relevanssi.
    – Howdy_McGee
    Commented Apr 22, 2020 at 14:15
  • @Howdy_McGee i forgot to mention i need it without any plugin. im aware of revelanssi btw. thx
    – Keusta
    Commented Apr 22, 2020 at 15:15

1 Answer 1

1

got a solution with https://stackoverflow.com/questions/15737408/php-find-all-occurrences-of-a-substring-in-a-string

$lastPos = 0;
$positions = array();

if($pos==''){}
else{
    while (($lastPos = strpos($content, $findme, $lastPos))!== false){
        $positions[] = $lastPos;
        $lastPos = $lastPos + strlen($findme);
        }

    // Displays 
    foreach ($positions as $eachPos){
        $pos = $eachPos;
        $exctractAfterQuery = substr($content,($pos+strlen($findme) ),40);
        $exctractBeforeQuery = substr($content,$pos-40,40);
        $newContent .= "[...".$exctractBeforeQuery.'<strong class="search-highlight">'.$findme."</strong>".$exctractAfterQuery."...]<br>";
        }
}

It works well and no need a plugin. hope this help someone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.