shie2’s diary

仕事とかエフェクターとかもろもろのために

【wordpress】Custom Fields Searchをちょっといじくった

事の起こり

お客さんから電話

「デザイナーにWordpressで店舗検索機能作ってもらってんけど
  うまく検索できないのよねぇ~ 助けて!」

との事で
対処したので、備忘録的に


そもそもなぜ?

要望から、

複数のカスタムフィールドで入力された内容全てに対して
自由入力で検索を行いたい

症状

対象データ
ソフマップ 秋葉原
住所 東京都北神田○○○

入力inputにソフマップ 神田」を入力すると
対象のソフマップ秋葉原
検索結果としてほしいのに、検索結果0件になる!

あ~。 SQLやなと
しかも、複数のカスタムフィールドをANDで検索してるし、空白で正しく分割してないなと


修正箇所

①検索ワードをスペースで分割

wp/wp-content/plugins/wp-custom-fields-search/extra_search_fields.php
384行目付近

<?php
function splitMultiValues($value){
    // return array($value); コメントアウト
    //空白文字での複数条件指定に対応
    $ary = preg_split('/[\s ]/u',$value);  //検索ワードをスペースで分割
    foreach($ary as $key => $row){  //分割したワードが''の状態なら削除
        if(empty($row)){
            unset($ary[$key]);
        }
    }
    return $ary;
}
?>

②検索対象カスタムフィールドを作るプラグインを作った。

ファイル構成

serach_box/
    serach_box.php
    js/
        input.js
    view/
        input.php

serach_box.php

<?php
/*
Plugin Name: search_box
Plugin URI: 検索用カスタムフィールド作成
Version: 1.0
Author: shie*2Works
*/

$sbSet = array(
    'sbUrl' => plugins_url('',__FILE__),
    'sbPath'=>dirname(__FILE__).'/',
    );
/**
 * 記事編集画面に検索文字列カスタムフィールドを追加
 */
function add_search_box() {
    // add_meta_box(表示されるボックスのHTMLのID, ラベル, 表示する内容を作成する関数名, 投稿タイプ, 表示方法)
    add_meta_box( 'post_serch_box_block','検索対象カスタムフィールド', 'create_serch_box_for_post', 'post', 'normal' );
}
add_action('admin_menu', 'add_search_box');
/**
 * 検索文字列カスタムフィールドのhtml出力
 * @return [type] [description]
 */
function create_serch_box_for_post(){
    global $sbSet;
    global $post;
    wp_nonce_field(wp_create_nonce(__FILE__), 'my_nonce');
    include_once($sbSet['sbPath'].'view/input.php');
}


function save_search_box($post_id){
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id; 
    }
    $my_nonce = isset($_POST['my_nonce']) ? $_POST['my_nonce'] : null;
    if(!wp_verify_nonce($my_nonce, wp_create_nonce(__FILE__))) {
        return $post_id;
    }
    $key ='search_box';
    if(isset($_POST[$key])){
        $val=$_POST[$key];
    }else{
        $val='';
    }
    if(get_post_meta($post_id, $key) == ""){
        add_post_meta($post_id, $key, $val, true);
    }elseif($val != get_post_meta($post_id, $key, true)){
        update_post_meta($post_id, $key, $val);
    }elseif($val == ""){
        delete_post_meta($post_id, $key, get_post_meta($post_id, $key, true));
    }
}
add_action('save_post', 'save_search_box');
?>

input.php

<textarea name="search_box" id="post_search_box_input" rows="3"><?php print get_post_meta($post->ID, 'search_box',TRUE);?></textarea>
<script type="text/javascript" src="<?php print $sbSet['sbUrl']; ?>/js/input.js"></script>

<style>
    #post_search_box_input{
        
        width: 100%;
        border:none;
        resize: none; 
    }
</style>

input.js

(function($) {
    $('#publish').click(function(){
        var metObj = $('#cftdiv');  //全カスタムフィールドが入ってるDivのidを指定する。
        var searchWord = '';
        //テキストボックス
        metObj.find('input[type="text"]').each(function(i){
            searchWord = searchWord + ' '+$(this).val();
        });
        //チェックボックス
        metObj.find('input[type="checkbox"]').each(function(i){
            elm = $(this);
            if(elm.prop('checked')){
                searchWord = searchWord + ' '+elm.val();
            }
        });
        //テキストボックス
        metObj.find('textarea').each(function(i){
            searchWord = searchWord + ' '+$(this).val();
        });
        //セレクトとかラジオボタンとかなかったから書いてない
        $('#post_search_box_input').val(searchWord);
    })
})(jQuery)

これをプラグインにしてFTPでアップしてプラグインを動かしせば完成