ウェブ
MONDAY 2020 / 3 / 16
コピペで超簡単!!投稿(カスタム投稿可)の管理画面をカスタムタクソノミーで絞り込めるようにする!
Text by Shinji Sato
こんにちは。
佐藤です。
wordpressでサイトを構築中にカスタムタクソノミーを使うことって結構ありますよね。
そして投稿の数が増えてくると(もしくは量が多くなることが想定される場合)設定したカスタムタクソノミーで投稿を絞り込みたくなる時って結構あると思います。
いつも必要だと思った場合に都度設定していたのですがだんだん面倒になってきたので簡単に設定できるようになる関数を作成しました。
せっかくなので共有します。
という訳で以下を「function.php」にコピペしましょう。
function add_custom_post_refine($my_post_type,$args = null){
if(is_string($args)){
$taxonomy_array = array(
$args,
);
}else{
$taxonomy_array = $args;
}
if(is_string($my_post_type) && !empty($taxonomy_array)){
add_filter('custom_post_refine',function($my_array) use($my_post_type,$taxonomy_array){
$my_array[$my_post_type] = $taxonomy_array;
return $my_array;
});
}
}
function add_custom_post_restrict(){
global $post_type;
$my_array = array();
$my_array = apply_filters('custom_post_refine',$my_array);
if(!empty($my_array)){
foreach($my_array as $my_post_type => $my_taxonomys){
if($post_type == $my_post_type){
$html = '';
foreach($my_taxonomys as $my_taxonomy){
$my_taxonomy_datas = get_taxonomies(array('name'=>$my_taxonomy),'objects');
$html .= <<<EOT
<input type="hidden" name="taxonomy" value="{$my_taxonomy}">
<select name="term">
<option value="">{$my_taxonomy_datas[$my_taxonomy]->label}一覧</option>
EOT;
$parent_terms = get_terms($my_taxonomy,array('parent'=>0));
foreach($parent_terms as $parent_term){
$html .= "<option value=\"{$parent_term->slug}\">{$parent_term->name}</option>";
$terms = get_terms($my_taxonomy,array('parent'=>$parent_term->term_id));
foreach($terms as $term){
$html .= "<option value=\"{$term->slug}\">- {$term->name}</option>";
}
}
$html .= '</select>';
}
echo $html;
}
}
}
}
add_action('restrict_manage_posts', 'add_custom_post_restrict');
あとは簡単。
function.phpで関数「add_custom_post_refine()」を呼び出し、引数に投稿タイプのスラッグとタクソノミーのスラッグを与えてやれば実装できます。
/*
第一引数に投稿タイプのスラッグ(string)
第二引数にタクソノミーのスラッグ(string)
*/
/* 使用例1: */
add_custom_post_refine('products','product_category');
// ※投稿タイプ「products」の一覧画面でタクソノミー「product_category」で絞り込めるようにする。
/* 使用例2: */
add_custom_post_refine('products',array('product_category1','product_category2'));
// ※タクソノミーは配列でも指定できます。

24
















