検索結果を郵便番号用に作成したカスタムフィールド(zip_code)でソートして表示させたい案件があったので、やってみました。郵便番号は、ハイフンを入れると結果が希望通りにならないので、フィールドにはハイフンなしで入力し、表示の際にハイフンをつける処理にしました。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function custom_main_query( $query ) { | |
| if ( is_admin() || !$query->is_main_query() ) return; | |
| $query->set('post_type', 'post' ); | |
| $query->set('post_status', 'publish'); | |
| $metaquery[] = array( | |
| 'meta1' => array( | |
| 'key' => 'zip_code', | |
| 'type' => 'NUMERIC' | |
| ), | |
| ); | |
| $query->set('meta_query',$metaquery); | |
| $query->set( 'order', 'ASC' ); | |
| $query->set('orderby',array( | |
| 'meta1' => 'ASC', | |
| ) | |
| ); | |
| } | |
| add_action( 'pre_get_posts', 'custom_main_query' ); |
ちなみに、ID順の場合は下記のような感じになりました。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $root = get_bloginfo('home'); | |
| $culCatSlg = $category_name;//表示中のカテゴリスラグを取得 | |
| $catArr = get_category_by_slug($culCatSlg ); //表示中のカテゴリ情報配列を取得 | |
| $pCatId = $catArr -> parent;//親カテゴリのIDを取得 | |
| if ($pCatId == "0") {//表示中のカテゴリが親なら | |
| $pCatId = $catArr -> term_id;//親カテゴリのID | |
| } else {//表示中のカテゴリが子カテゴリなら | |
| $cCatNam = $catArr -> name;//子カテゴリ名を取得 | |
| } | |
| $pCatArr = get_category($pCatId);//親カテゴリ情報配列を取得 | |
| $pCatNam = $pCatArr -> name;//親カテゴリ名を取得 | |
| $pCatSlg = $pCatArr -> slug;//親カテゴリスラグを取得 | |
| ?> | |
| <h2 class="entry-title"><?php echo $pCatNam ?><?php if ($cCatNam != "") echo " ― ".$cCatNam ?></h2> | |
| <?php | |
| $cCatArr = get_terms( 'category', 'child_of='.$pCatId.'&orderby=ID&order=ASC' ); //子カテゴリ情報配列の取得 | |
| if (count($cCatArr) > 0)://子カテゴリが存在するなら | |
| ?> | |
| <select onChange="window.location.href=this.options[this.selectedIndex].value;"> | |
| <option value="">市町村をお選びください</option> | |
| <?php foreach( $cCatArr as $cCat ): | |
| $cCatSlg = $cCat -> slug;//子カテゴリスラグ | |
| $cCatNam = $cCat -> name;//子カテゴリ名 | |
| $category_id = $cCat -> term_id;//子カテゴリID | |
| $category_link = get_term_link( $category_id ); | |
| ?> | |
| <option value="<?php echo $category_link ?>"><?php echo $cCatNam ?></option> | |
| <?php endforeach; ?> | |
| </select> | |
| <?php endif; ?> | |
| <?php | |
| $children = get_term_children($cat, 'category');// 子カテゴリーを取得 | |
| if(!empty($children)): // 子カテゴリーありなら非表示 | |
| ?> | |
| <?php else: ?> | |
| <?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?> | |
| <?php while (have_posts() ) : the_post(); ?> | |
| <?php get_template_part('inc/result','loop'); ?> | |
| <?php endwhile; // end of the loop. ?> | |
| <?php endif; ?> |