How to set one search field to search in post_title and an another search field to search in post_content only, using "set" method in pre_get_post action?

1 Answer 1

  1. Adding the following code in functions.php customize WP search for title only

function search_by_title_only( $search, &$wp_query ) { global $wpdb; if ( empty( $search ) ) return $search; // skip processing - no search term in query $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}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; $searchand = ' AND '; } 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' );

  1. Search in post content is default search option in WP.
  • From your answer my conclusion is: pre_get_post action can't do what I want. But I didn't understand how can I differentiate two fields and say to WP that phrase_1 is for post_title only and phrase_2 is for post_content only, if I use field_name_1 and field_name_2 in search form? Or I must always use default search field and add new one for title? How can I then limit the default search field only for post_content?
    – user111275
    Commented Jan 23, 2017 at 12:59
  • You haven't differentiate two fields in search form. One field will search posts. But, if a checkbox or something like that checked, filter that search by title only. Else, search default, which search on post content only. Can I share idea? Commented Jan 23, 2017 at 15:47
  • But I want to differentiate two fields, one for each of two main searchable post table fields. If this is not possible without writing custom sql then the idea to alter the query through hooks fails. If you have an idea, please share it. Thanks.
    – user111275
    Commented Jan 24, 2017 at 16:57
  • two field with two search form? Please share your design for better understanding. I assume that you want a search like smashingmagazine.com/wp-content/uploads/2016/02/…. Is it? Commented Jan 25, 2017 at 6:56
  • No no no. One search form with two search fields. One for post_title and one for post_content. I want to use pre_get_posts to alter wp_query. If pre_get_posts action can't do the job, how to solve?
    – user111275
    Commented Jan 25, 2017 at 10:49

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.