teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

再改良

2019/12/26 02:41

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -46,6 +46,7 @@
46
46
  $cat_info = get_the_category($post->ID);
47
47
  $i = 0;
48
48
  $count = count($cat_info);
49
+ $categories = [];
49
50
  while($i < $count) {
50
51
  $cat = $cat_info[$i];
51
52
  $cat_name = $cat->cat_name;
@@ -55,7 +56,6 @@
55
56
  echo $cat_name;
56
57
  $i++;
57
58
  } else {
58
- $categories = [];
59
59
  $ancestor = get_ancestors($cat_id, 'category');
60
60
  $ancestor = array_pop($ancestor);
61
61
  $categories[] = $ancestor;

1

ループを書き換えてみました

2019/12/26 02:41

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -38,4 +38,30 @@
38
38
  ### やったこと(echoでHTMLに直接表示されてしまいました)
39
39
  ```
40
40
  <?php if(get_cat_all(array(get_cat_all()))): ?>
41
+ ```
42
+
43
+ ### 改良版
44
+ ```
45
+ global $post;
46
+ $cat_info = get_the_category($post->ID);
47
+ $i = 0;
48
+ $count = count($cat_info);
49
+ while($i < $count) {
50
+ $cat = $cat_info[$i];
51
+ $cat_name = $cat->cat_name;
52
+ $cat_parent = $cat->parent;
53
+ $cat_id = $cat->cat_ID;
54
+ if($cat_parent == 0) {
55
+ echo $cat_name;
56
+ $i++;
57
+ } else {
58
+ $categories = [];
59
+ $ancestor = get_ancestors($cat_id, 'category');
60
+ $ancestor = array_pop($ancestor);
61
+ $categories[] = $ancestor;
62
+ $i++;
63
+ }
64
+ //ループ終了後に
65
+ return $categories;
66
+ }
41
67
  ```