搜索时避免查看发布内容

时间:2018-04-23 09:09:02

标签: wordpress

我使用WP_Query创建了一个用于搜索帖子的查询。以下是查询

$args = array(
    's' => 'Keyword'
);
$the_query = new WP_Query( $args );

但论证的论点是'总是关注post_title和post_content。我想改变它,所以它只调查post_title而不是post_content。怎么做?

1 个答案:

答案 0 :(得分:1)

首先你需要修改wp的搜索功能,使用posts_search过滤器钩子检查这个Link,然后运行你的查询和参数。 之后,您需要在使用后删除该钩子。 示例代码如下:

<?php
function wpse_11826_search_by_title( $search, $wp_query ) {
    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
        global $wpdb;

        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';

        $search = array();

        foreach ( ( array ) $q['search_terms'] as $term )
            $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );

        if ( ! is_user_logged_in() )
            $search[] = "$wpdb->posts.post_password = ''";

        $search = ' AND ' . implode( ' AND ', $search );
    }

    return $search;
}

add_filter( 'posts_search', 'wpse_11826_search_by_title', 10, 2 );

$args = array(
    's' => 'Keyword'
);
$the_query = new WP_Query( $args );

remove_filter( 'posts_search', 'wpse_11826_search_by_title', 500 );


//Then your code goes here....


?>