最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Search Results Page filter by page title

programmeradmin0浏览0评论

How can i edit the search results page embedded in OceanWP theme, so that the page with a title similar to the word i entered in the search bar show up first or at least highlighted?

How can i edit the search results page embedded in OceanWP theme, so that the page with a title similar to the word i entered in the search bar show up first or at least highlighted?

Share Improve this question asked Jun 26, 2019 at 9:39 sihamxxisihamxxi 351 silver badge6 bronze badges 1
  • Is this just a matter of presentation, or are you trying to change / improve the search results that it generates? I'd guess that the theme just uses WordPress's built-in search, not provides its own, so it's probably a case of finding a replacement search plugin. I don't know one to recommend sorry. – Rup Commented Jun 26, 2019 at 9:54
Add a comment  | 

1 Answer 1

Reset to default 1

While I think you are looking for a plugin, I think this answer might help some people who search for a similar answer. If you have access to your functions.php file, you can easily make this happen.

First we'll alter the orderby parameter of the search query in order to filter them by page title. Here is a snippet that I tested and will alter you search results page and order it by title, ascending.

//Filter the search by title for posts
function filter_search_by_title($query){
    if($query->is_search() && $query->is_main_query()){
      $query->set('post_type', array('post'));
      $query->set('orderby', 'title');
      $query->set('order', 'ASC');
  }
  return $query;
}

add_action('pre_get_posts', 'filter_search_by_title');

Next, regarding the highlighting, here is a piece that will go through your the_excerpt and the_title on the search results page, and will add a <strong> around each instance of the string searched. Obviously you can change that to whatever you'd like in order to style it.

function highlight_search_results($content){
     if(is_search()){
       $search_string = get_query_var('s');
       $keys = explode(" ",$search_string);
       $content = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="highligh-search">'.$search_string.'</strong>', $content);
     }
     return $content;
}
add_filter('the_excerpt', 'highlight_search_results');
add_filter('the_title', 'highlight_search_results');

Hope that helps!!

发布评论

评论列表(0)

  1. 暂无评论