Site Search

jQueryでWordPressにAjax検索を実装する

ナビゲーション改善のために検索をAjaxにしてリアルタイムにできるようにしました。WordPressなら楽々実装できます。本当は誰でも簡単に使えるようにコピペできるような内容にしようと思ったりもしたんですけど、残念ながら面倒くさくなったので、僕がこのブログに実装したコードを貼るだけにします。そうです、これが手抜きです。

search.phpをXHR対応にする(JSONで返すようにする)

下のソースコードをsearch.phpの頭にペタっと。あ、テンプレート名とか書いてあるコメントの下です。

<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    query_posts($query_string . '&posts_per_page=100');
    $response = array(
        'posts' => array()
    );
    while (have_posts()) {
        the_post();
        $response['posts'][] = array(
            'title' => the_title("","",false),
            'link' => get_permalink() // descriptionとか色々追加できる
        );
    }
    echo json_encode($response);
    exit(0);
}
?>

これでXHRでリクエストするとこんな感じのJSONが返ってきます。

{"posts":[{"title":"2010\u5e74\u306e\u4eba\u6c17\u30a8\u30f3\u30c8\u30ea\u30fc\u307e\u3068\u3081\u307e\u3057\u305f\u3093\uff01","link":"http:\/\/5509.me\/log\/popular-entries"},{"title":"\u30c6\u30ad\u30b9\u30c8\u30dc\u30c3\u30af\u30b9\u306e\u6b8b\u308a\u5165\u529b\u6587\u5b57\u6570\u3092\u30b7\u30f3\u30d7\u30eb\u306b\u8868\u793a\u3059\u308bjQuery\u30d7\u30e9\u30b0\u30a4\u30f3 m5simpleTextCount","link":"http:\/\/5509.me\/log\/m5simpletextcount"}....]}

JSソース

トリガーは検索ボックスに何か入力したときにしています。エンター押したときでもいいです。そのときは.submit()に$.ajax()を書くだけなのでもっと簡単です。とりあえずブログの検索はβなので、もしかするとsubmitタイプに変えるかもしれないです。

var xhr,
    keyword = $("#s"),
    searchResult = $("#searchResult").hide(),
    searchResultList = $("#searchResultList"),
    searchLoading = $("#searchLoading"),
    typeTimer;

keyword
    .click(function() {
        var _txt = this.value;
        if ( _txt || _txt.length !== 0 ) {
            searchResult.show();
        }
    })
    .keyup(function() {
        var _txt = this.value;
        // valueがなければ何もしないよ
        if ( !_txt || _txt.length === 0 ) {
            searchResult.hide();
            return false;
        }
        // 間を置かずに入力している場合はキューを削除する
        if ( typeTimer ) {
            clearTimeout(typeTimer);
        }
        if ( xhr ) {
            xhr.abort();
        }
        // typeTimerでkeyupのする度にリクエストするのではなくて
        // 350ミリセカンド以上間があいた場合にリクエストする
        typeTimer = setTimeout(function() {
            searchResultList.html("").hide();
            searchLoading.show();
            searchResult.show();
            xhr = $.ajax({
                // search.phpではなくて / に投げる(WPの検索仕様
                url: "/",
                // 検索クエリを投げる
                data: {
                    s: _txt
                },
                // GETでいいねん
                type: "GET",
                // jsonで投げるねん
                dataType: "json",
                error: function() {
                    // errorのときのsomething
                },
                success: function(json) {
                    searchLoading.hide();
                    var _posts = json.posts,
                        _postsLen = _posts.length,
                        i;
                    if ( !_posts || _postsLen === 0 ) {
                        searchResultList.append("<li>なにもねーわ</li>");
                    } else {
                        for ( i = 0; i < _postsLen; i++ ) {
                            searchResultList.append(
                                "<li><a href=\"" + _posts[i].link + "\">" + _posts[i].title + "</a></li>"
                            );
                        }
                    }
                    searchResultList.show();
                }
            });
        }, 350)
    });

なんとこれだけで実装できたっていう話でしたー。本文めっちゃ短い!手抜きの記事ですなぁ。おかしいなぁ、本当なら見た人みんながあれ!簡単!実装してみたい!っていうような内容になるはずやったのに・・・と思ってコメントを少し入れておきました。。

何か役に立つことがあったらシェアしてみてください

このエントリーをはてなブックマークに追加

Leave a comment

Comment Form
Name(required)
Email(required)
URL
Comment(required)
You can use some HTML tags for decorating texts.
(a, blockquote, ul, ol, strong, em)

Trackbacks: 0

Trackback URL for this entry
Listed below are links to weblogs that reference
jQueryでWordPressにAjax検索を実装する from 5509

Author

nori
nori
- UI Engineer
Location
- 35.671643, 139.710752