【ワードプレス】ワードプレスで現在ページの親カテゴリスラッグを取得する方法
ワードプレスで現在ページの親カテゴリスラッグを取得する方法です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | if(! function_exists('get_category_parent_id')): function get_category_parent_id($cat_id = FALSE) { global $post; if(is_category()){ $cat = get_queried_object(); }else{ // post_idのすべてのカテゴリを取得 $cats = get_the_category($post->ID); // cat_idに指定があったら指定のカテゴリオブジェクトを取得 if($cat_id){ $cats = array_filter($cats, function($cat) use($cat_id){ return ($cat->term_id == $cat_id); }); $cats = array_values($cats); } if(empty($cats)) return FALSE; $cat = $cats[0]; } // category_parentが0ではない場合、親カテゴリIDを返す if($cat->category_parent){ $category_parent = get_category($cat->category_parent); return $category_parent->slug; }else{ return $cat->slug; } } endif; |
コメントを投稿するにはログインが必要です。