タイトルを投稿するために検索を制限する方法は?


26

タイトルを投稿するために検索を制限する方法はありますか?query.phpコアファイルを変更できることは知っていますが、フックでそれを行う方法が必要です。

前もって感謝します!

回答:


31

トリックを実行するフィルターを次に示します。テーマfunctions.phpまたはプラグインにドロップします。

/**
 * Search SQL filter for matching against post title only.
 *
 * @link    http://wordpress.stackexchange.com/a/11826/1685
 *
 * @param   string      $search
 * @param   WP_Query    $wp_query
 */
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 );

コードが削除されWP_Queryていることを除いて、ほとんどのコードはクラスからコピーpost_content LIKEされています。

UPDATE: Removed deprecated like_escape() since 4.0


great works perfectly, I knew there was a filter for this, couldn't find it anywhere in the codex, thanks a lot!
— Javier Villanueva

@TheDeadMedic I just tried it on my blog and that particular query now returns no result at all, with or without this code. Any ideas?
— Ashfame

Now its working as usual without the code but the code didn't work for me. It showed the same results :/
— Ashfame

@Ashfame I have revised my answer.
— TheDeadMedic

1
PHP message: PHP Fatal error: Call to undefined method wpdb::esc_like() --- If you have an older WordPress, this is a new function as of WP 4.0
— PJ Brunet
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.