如何限制 wp-admin 只搜索标题

How to limit wp-admin to search only titles

我试图将 WP 管理区域中的搜索限制为 post 标题。

我找到了提供建议的代码,但是,这并没有将搜索仅限于 post/page 标题:

add_filter( 'posts_search', 'wpse_45153_filter_search', null, 2 );
function wpse_45153_filter_search( $search, $a_wp_query ) {
    if ( !is_admin() ) return $search; // work only in the dashboard

$search = preg_replace( "# OR \(.*posts\.post_content LIKE \'%.*%\'\)#", "", $search );

return $search;
}

试试这个:

add_filter( 'posts_search', 'search_by_title_only', 10, 2 );
function search_by_title_only( $search, $wp_query ) {
    if ( !is_admin() || empty( $search ) ){
        return $search;
    }
    global $wpdb;
    $q = $wp_query->query_vars;
    $x = ! empty( $q['exact'] ) ? '' : '%';
    $search = '';
    $searchand = '';
    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( $wpdb->esc_like( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$x}{$term}{$x}')";
        $searchand = ' AND ';
    }
    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
    }
    return $search;
}

它本质上是在查询的末尾添加了另一个子句(使用 'AND'),其中名称必须包含所提供的搜索字符串。