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

时间:2019-01-11 23:51:14

标签: wordpress wp-admin

我正试图将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;
}

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

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”),其中名称必须包含所提供的搜索字符串。