[WordPress]カスタム投稿タイプ記事一覧にタクソノミー絞り込み機能を追加

functions.php

/**
 * WP_Termの配列の各要素にterm_ordersを設定する
 *
 * @param array $terms
 * 
 */
function set_parents_term_orders_to_terms(&$terms)
{
    if(empty($terms)){
        return;
    }
    foreach ($terms as $i => $term) {
        $terms[$i]->term_orders = [$term->term_order];
        if(!empty($term->parent)){
            $tmp = $term;
            while(!empty($tmp->parent)){
                $tmp_id = $tmp->term_id;
                foreach ($terms as $j => $term_) {
                    if($tmp->parent === $term_->term_id){
                        array_unshift($terms[$i]->term_orders,$term_->term_order);
                        $tmp = $term_;
                        break;
                    }
                }
                if($tmp_id === $tmp->term_id){
                    break;
                }
            }
        }
    }
}
/**
 * WP_Termの配列をterm_ordersに則ってソートする
 * set_parents_term_orders_to_terms を実行してから使用する
 *
 * @param array $terms
 * 
 */
function sort_terms_by_term_orders(&$terms)
{
    usort($terms,function($a,$b){
        $imax = max(count($a->term_orders),count($b->term_orders));
        for($i=0;$i<$imax;$i++){
            if(count($a->term_orders) <= $i){
                return -1;
            }
            if(count($b->term_orders) <= $i){
                return 1;
            }
            if($a->term_orders[$i] === $b->term_orders[$i]){
                continue;
            }
            return ($a->term_orders[$i] > $b->term_orders[$i]) ? 1 : -1;
        }
    });
}
/**
 * 管理画面記事一覧カテゴリフィルタ追加
 */
function add_post_taxonomy_restrict_filter()
{
global $post_type;
if($post_type === 'カスタム投稿タイプ'){
?>
<select name="タクソノミー">
<option value="">カテゴリーを指定する</option>
<?php
$terms = get_terms('タクソノミー');
/*
プラグイン「Category Order and Taxonomy Terms Order」導入済みの場合
set_parents_term_orders_to_terms($terms);
sort_terms_by_term_orders($terms);
*/
foreach ($terms as $term) { ?>
<option value="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
<?php
}
}
add_action('restrict_manage_posts', 'add_post_taxonomy_restrict_filter');