• Hello,
    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 ?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Add this to your theme’s functions.php file.

    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}' AND $wpdb->posts.post_type = 'post')) OR ({$searchand}($wpdb->posts.post_content LIKE '{$n}{$term}{$n}' AND $wpdb->posts.post_type = 'page'))";
            $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', 500, 2 );
    Thread Starter andriuss

    (@andriuss)

    Thank you very much! it works! 😉

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘WordPress Custom Search By Post Type’ is closed to new replies.