我试图将WP管理区域中的搜索限制为仅发布标题。
我找到了提供建议的代码,但是,这并不仅限于帖子/页面标题:
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"),其中名称必须包含提供的搜索字符串。