Advertisement
LABE

[WP] the_category(): display only parents

Apr 13th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.71 KB | None | 0 0
  1. /* https://ja.wordpress.org/support/topic/ループ内で、親と子カテゴリーを選択したとき、/ */
  2. function my_category_list( $categories, $post_id ) {
  3.     $cats = $categories;
  4.     $cats_ID = array_map( function ( $cat ) {
  5.         return $cat->term_id;
  6.     }, $cats );
  7.     foreach ( $categories as $key => $category ) {
  8.         $ancestor = $category;
  9.         while ( ! empty( $ancestor->parent ) && $ancestor = get_category( $ancestor->parent ) ) {
  10.             if ( in_array( $ancestor->term_id, $cats_ID, true ) ) {
  11.                 unset( $cats[ $key ] );
  12.                 break;
  13.             }
  14.         }
  15.     }
  16.     return $cats;
  17. }
  18. add_filter( 'the_category_list', 'my_category_list', 10, 2 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement