简体   繁体   中英

How to search by the title in wordpress WP_Query?

From the wordpress offical document website , there are a search parameter

http://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter

which is &s={keywords}

However, I wonder is this search is based on everything of the Post? that means if I provide &s=book , then if a Post has a name = "abc" which is a category of "book", it still include in the search result. Are there any way to specific the search to title_plain only?

http://test.com/?json=get_posts&status=published&orderby=date&order=DESC&lang=en&s=eng&cat=9,10,14,15

Thanks for help.

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', 500, 2 );

why would you want to use wp_query for searching posts based only on title .. when you got a pre built function for it in wordpress ??

Get Page By Title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM