customization - How to loop for every result found in the_content() when using the search query?

im doing a custom search result page with function that extract from the_content() some words before and after the searc

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";
        }                                                                                                                                                                                                                                                                                       
    }
}

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";
        }                                                                                                                                                                                                                                                                                       
    }
}
Share Improve this question edited Apr 22, 2020 at 15:17 Keusta asked Apr 22, 2020 at 13:17 KeustaKeusta 216 bronze badges 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
Add a comment  | 

1 Answer 1

Reset to default 1

got a solution with https://stackoverflow/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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744543475a4579868.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信