0

SearchResultsPage

I have designed and developed a responsive Wordpress site that is almost ready for launch for a client who is an actor and producer. I have been stuck on my requirements for the search results page for three days.

My EXCERPT is far too long and includes repeated text from the Home page no matter what the search is for. Under the white links to the posts and pages for the search results, I want an excerpt of no more than 30 words which includes the search keyword (in this case the search keyword being “Ginsberg”) highlighted. So, a snippet of about 30 words, including the search term highlighted. That’s what I can’t get. When I have that, I have the search page I want.

I have spent hours Googling and searching this on Stack Exchange and Stack Overflow, as well as attempts at finding the PHP logic required myself and failing. So if there is a solution to this already here, it’s well hidden!!

WHAT I DO HAVE AND WHAT I’M HAPPY WITH IS: Say I do a search for the Beat Poet “Ginsberg” (screen shot attached). I get a main heading saying “2 results found for “Ginsberg”. Under that a smaller heading saying “Your ‘Ginsberg search results can be found at”” then below that I get a nicely styled list of two links to the two relevant pages. I want all that. That’s great.

MY SEARCH FORM:

<div class="search-cont">                         
        <form class="searchinput" method="get" action="<?php echo home_url(); ?>" role="search">
        <input type="search" class="searchinput" placeholder="<?php echo esc_attr_x( 'Click icon or hit enter to search..', 'placeholder' ) ?>" value="<?php get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
        <button type="submit" role="button" class="search-btn"/><i class="fa fa-search" aria-hidden="true"></i></button>
        </form>
        </div>

=--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- MY SEARCH PAGE:

<div class="searchresultsbox"> 
                  <?php global $wp_query;?>
      <h2> <?php echo $wp_query->found_posts; ?><?php _e( ' results found for', 'locale' ); ?>: "<?php the_search_query(); ?>"</h2>
                <?php if ( have_posts() ) { ?>
            <h3><?php printf( __( 'Your "%s" search results can be found at:', 'ptpisblogging' ), get_search_query() ); ?></h3>
            <?php while ( have_posts() ) { the_post(); ?>
                 <h3><a href="<?php echo get_permalink(); ?>">
                   <?php the_title();  ?>
                 </a></h3> 
                 <?php //echo substr(get_the_excerpt(), 0, 2); ?>
                 <div class="h-readmore"> <a href="<?php //the_permalink(); ?>"></a></div>
               <?php
 $args=array('s'=>'test','order'=> 'DESC', 'posts_per_page'=>get_option('posts_per_page'));
   $query=new WP_Query($args);
  if( $query->have_posts()): 
  while( $query->have_posts()): $query->the_post();
 {
   echo $post->post_title;
   echo $post->post_content;
 }
 endwhile; 
 else:
 endif;
 ?>
 <?php } ?>
 <?php paginate_links(); ?>
        <?php } ?>
    </div>
  </div>
</div>
<param name="" value="">
                </div><!-- /searchresultsbox -->
            </div><!-- /collcelltwo -->
        </div><!-- /tb-one-row --> 
    </div><!-- /tb-one -->

=--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- IN 'functions.php'

add_action( 'pre_get_posts', function( $query ) {
        // Check that it is the query we want to change: front-end search query
        if( $query->is_main_query() && ! is_admin() && $query->is_search() ) {
        // Change the query parameters
        $query->set( 'posts_per_page', 4 );
        }
        } );

I am extremely grateful for your input. Thank you!! Keith

3 Answers 3

1

This will helpful for you... Use this code at function.php

function wps_highlight_results($text){
     if(is_search()){
          $sr = get_query_var('s');
          $keys = explode(" ",$sr);
          $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
0

Use str_replace to replace all occurances of the word to highlight with a around the word. Something like

// $searchresult = result of search process, 
//$highlightword = word you want to highlight
$searchresult = str_replace( $highlightword, 
     "<span style='background-color:#ffff00;'>$highlightword</span>",
      $searchresult );

Adjust the background-color to what you want to use.

To limit the number of words in the search result, see the answer to a similar question: https://stackoverflow.com/questions/965235/how-can-i-truncate-a-string-to-the-first-20-words-in-php .

Edited: changed background color to yellow (#ffff00);

10
  • Hi Rick, Thank you for the '$searchresult = str_replace' expression above, but I can't see how to apply it to my search page. Could you please post an example of how you'd apply the method to my search page code? Much appreciated. Many thanks. Commented Jul 20, 2017 at 19:19
  • Assume that the contents of the search result are in the $searchresult variable (you get to do that part). And that the $highlightword variable contains the string/word you want to highlight. The code fragment will put a <span> that contains a background color of yellow(#ffff00) (#000 is black) around that $highlightword string. Commented Jul 20, 2017 at 19:56
  • I suppose you could also do some Javascript that would highlight the search word after the page is loaded. I'm not a Javascript expert (not even close), but perhaps this answer might be helpful for that: stackoverflow.com/questions/8644428/… . Commented Jul 20, 2017 at 21:29
  • Hi Rick, I tried several ways of injecting your '$searchresult = str_replace' method. None worked. It's also heading for 11 pm here in London (UK). I'll try again when I'm fresh. There should be a PHP / Wordpress solution to this. I think delving into JavaScript would be hackey. What it comes down to is my lack of Wordpress-PHP logic. Thanks again for your help. Commented Jul 20, 2017 at 21:36
  • Just before the echo $post->post_content in the search results page (which outputs the results of the search), set $searchresults = $post->post_content . Then also set $highlightword = $_POST('s') . Then put the str_replace just after that. Then echo $searchresults . Remove the echo $post->post_content; (replaced by the echo $searchresults ). There's also some jQuery techniques that could be used; see the link in the 3rd comment above here. Commented Jul 20, 2017 at 22:20
0

In search page, after this loop

<?php if( have_posts() ) : while( have_posts() ) : the_post() ?>

add this

<?php 
$excerpt = get_the_excerpt(); 
$keys    = explode(" ",$s); 
$excerpt = preg_replace(
    '/('.implode('|', $keys) .')/iu', 
    '<strong class="search-excerpt">\0</strong>', 
    $excerpt
); 
?>

Add at the place where you want to see Excerpt add this

<?php echo $excerpt; ?>

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.