Is it possible:

If post type is post, search only in post title. If post type is page, search only in post content.

I was trying in any ways but didnt worked, maybe someone could help me ?


Yes, it is possible. You will have to use your custom SQL query though.

Use posts_where filter to modify the query.

function posts_where( $where ) {
    if( !is_admin() ) {
        $where = <YOUR CONDITION>;
    return $where;
add_filter( 'posts_where' , 'posts_where' );

Your condition should look something like this:

post_status = 'publish' AND ((post_type = 'post' AND post_title LIKE <QUERY>) OR (post_type = 'page' AND post_content LIKE <QUERY>))

You should also make sure, that you will modify only main query and not all of them. You can add filter just before main query (i.e. using pre_get_posts action) and remove it just after or even inside this filter, I guess.

  • Thank you very much! I will try tomorrow, because all day was trying to figure out this ... I was trying in wp-includes/query.php in get_posts funcion... Maybe would be easier to use filter ? how can I implement this ? I am sure that i need to change condition there: $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
    – andys
    Jul 11 '13 at 19:17
  • Ok I have several post types: Forum, reply, topic, post, page. I need that if reply when search in post content, if topic when search in post title, and the others search in post title and in post content ? Did I made right? $search .= "{$searchand}(((post_type != 'topic' OR post_type != 'reply') AND ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}' OR $wpdb->posts.post_content LIKE '{$n}{$term}{$n}')) OR (post_type = 'reply' AND $wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR (post_type = 'topic' AND $wpdb->posts.post_title LIKE '{$n}{$term}{$n}'))";
    – andys
    Jul 11 '13 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.