質問編集履歴

2

再改良

2019/12/26 02:41

投稿

退会済みユーザー
test CHANGED
File without changes
test CHANGED
@@ -94,6 +94,8 @@
94
94
 
95
95
  $count = count($cat_info);
96
96
 
97
+ $categories = [];
98
+
97
99
  while($i < $count) {
98
100
 
99
101
  $cat = $cat_info[$i];
@@ -112,8 +114,6 @@
112
114
 
113
115
  } else {
114
116
 
115
- $categories = [];
116
-
117
117
  $ancestor = get_ancestors($cat_id, 'category');
118
118
 
119
119
  $ancestor = array_pop($ancestor);

1

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

2019/12/26 02:41

投稿

退会済みユーザー
test CHANGED
File without changes
test CHANGED
@@ -79,3 +79,55 @@
79
79
  <?php if(get_cat_all(array(get_cat_all()))): ?>
80
80
 
81
81
  ```
82
+
83
+
84
+
85
+ ### 改良版
86
+
87
+ ```
88
+
89
+ global $post;
90
+
91
+ $cat_info = get_the_category($post->ID);
92
+
93
+ $i = 0;
94
+
95
+ $count = count($cat_info);
96
+
97
+ while($i < $count) {
98
+
99
+ $cat = $cat_info[$i];
100
+
101
+ $cat_name = $cat->cat_name;
102
+
103
+ $cat_parent = $cat->parent;
104
+
105
+ $cat_id = $cat->cat_ID;
106
+
107
+ if($cat_parent == 0) {
108
+
109
+ echo $cat_name;
110
+
111
+ $i++;
112
+
113
+ } else {
114
+
115
+ $categories = [];
116
+
117
+ $ancestor = get_ancestors($cat_id, 'category');
118
+
119
+ $ancestor = array_pop($ancestor);
120
+
121
+ $categories[] = $ancestor;
122
+
123
+ $i++;
124
+
125
+ }
126
+
127
+ //ループ終了後に
128
+
129
+ return $categories;
130
+
131
+ }
132
+
133
+ ```