如何仅在帖子标题中搜索 - wp_query

Avi*_*igo 1 ajax wordpress

我在帖子过滤器表单中添加了一个文本字段,并使用 s= 参数使搜索工作。但是如何只在帖子的标题中搜索(而不是在内容中)?

HTML:

<input type="text" name="search" placeholder="Search..." value="">
<button>Filter</button>
Run Code Online (Sandbox Code Playgroud)

PHP:

    $args = array(
        'post_type' => $_POST['posttype'], 
        'orderby' => $_POST['orderby'], 
        'order' => $_POST['order'],
        's' => $_POST['search']
    );
Run Code Online (Sandbox Code Playgroud)

Tan*_*tel 6

找到您需要在其上实现搜索功能的文件,并将以下代码添加到您的文件中。

$args = array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'orderby' => $_POST['orderby'], 
    'order' => $_POST['order'],
    'search_prod_title' => $_POST['search'],
);
add_filter( 'posts_where', 'title_filter', 10, 2 );
$query = new WP_Query($args);
remove_filter( 'posts_where', 'title_filter', 10, 2 );
Run Code Online (Sandbox Code Playgroud)

要在 WordPress 查询中搜索标题,您需要向 WordPress 主题的 functions.php 文件添加一个函数。

function title_filter( $where, &$wp_query ){
    global $wpdb;
    if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
    }
    return $where;
}
Run Code Online (Sandbox Code Playgroud)