如何在wordpress WP_Query中按标题搜索?

时间:2014-04-29 04:03:45

标签: php html json wordpress wordpress-plugin

从wordpress官方文档网站,有一个搜索参数

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

&s={keywords}

但是,我想知道这个搜索是基于邮政的一切吗?这意味着如果我提供&s=book,那么如果帖子有一个名字=" abc"这是" book"的一个类别,它仍然包含在搜索结果中。有没有办法将搜索特定到title_plain?

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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 );

答案 1 :(得分:1)

为什么你要使用wp_query只根据标题来搜索帖子..当你在wordpress中为它预先构建的函数时?

<强> Get Page By Title