R
R
Rostislav2016-09-08 13:01:31
CMS
Rostislav, 2016-09-08 13:01:31

How to make in Wordpress so that the search searches first by headings, and if nothing is found, then by the text of the articles?

Here it is described how to search only by titles
ixmaster.net/nastroyka-wp/poisk-tolko-po-zagolovku...
only in the text of the article.
The question is how to combine these pieces of code so that it searches immediately by the title (the title of the article), and if nothing is found, then by the text of the article.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor, 2016-09-08
@DarkSir

You can try like this:

function __search_by_title_only( $search, &$wp_query ){
  global $wpdb;
  if ( empty( $search ) ) return $search;

  $searchTitle = $wpdb->posts.post_title;
  $searchContent = $wpdb->posts.post_content;

  $q = $wp_query->query_vars;
  $n = ! empty( $q['exact'] ) ? '' : '%';
  $search =
  $searchand = '';

  foreach ( (array) $q['search_terms'] as $term ) {
    $term = esc_sql( like_escape( $term ) );
    $search .= "{$searchand}($searchTitle LIKE '{$n}{$term}{$n}')";
    $searchand = ' AND ';
    $search .= "{$searchand}($searchContent LIKE '{$n}{$term}{$n}')";
  }

  if ( ! empty( $search ) ) {
    $search = " AND ({$search}) ";
  if ( ! is_user_logged_in() )
    $search .= " AND ($wpdb->posts.post_password = '') ";
  }
  return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

R
Rostislav, 2016-09-08
@boarworm

I probably didn't explain well.
The search first searches ONLY by title ($wpdb->posts.post_title)
If there are results, it displays them.
If there are no results, then the search looks in the texts of the articles themselves ($wpdb->posts.post_content)
If there are results, it displays them.
If not, it displays "Nothing found".
I don’t understand how in this case to make one request to the database (search by title), check the answer for emptiness, and if the answer is empty, then make a second request (search by text)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question