回答編集履歴

1

サンプルコードを追記しました。

2018/10/03 10:59

投稿

marlboro_tata
marlboro_tata

スコア525

test CHANGED
@@ -38,4 +38,166 @@
38
38
 
39
39
 
40
40
 
41
- 今のコードには、「親カテゴリに属する子カテゴリを取得してループする」という部分がまるっと抜けています。(時間があれば具体的なコードを追記します)
41
+ 今のコードには、「親カテゴリに属する子カテゴリを取得してループする」という部分がまるっと抜けています。
42
+
43
+
44
+
45
+ サンプルのコードは以下の通りです。WP_Queryではなく、get_posts()を使いました。
46
+
47
+ 親カテゴリの記事一覧を取得するときに、やはり、子カテゴリの記事も合わせて取ってきてしまうので、
48
+
49
+ 'tax_query' で 'include_children' => false を追記することで、親カテゴリ直下の記事のみ取り出せました。
50
+
51
+
52
+
53
+ ```PHP
54
+
55
+ <?php
56
+
57
+ $args = array(
58
+
59
+ 'parent' => 0,
60
+
61
+ 'hide_empty' => 0
62
+
63
+ );
64
+
65
+ $categories = get_categories($args);
66
+
67
+ //以下から親カテゴリのループ
68
+
69
+ foreach($categories as $category) :
70
+
71
+ ?>
72
+
73
+ <dl>
74
+
75
+ <dt>
76
+
77
+ <a href="<?php echo get_category_link( $category->term_id ); ?>"><?php echo $category->cat_name; ?></a>(親カテゴリアーカイブへのリンク)
78
+
79
+ </dt>
80
+
81
+ <dd>
82
+
83
+ <ul>
84
+
85
+ <?php
86
+
87
+ $args = array(
88
+
89
+ 'parent' => $category->term_id,
90
+
91
+ 'hide_empty' => 0
92
+
93
+ );
94
+
95
+ $children = get_categories($args);
96
+
97
+ //以下から子カテゴリのループ
98
+
99
+ if($children):
100
+
101
+ foreach($children as $child) :
102
+
103
+ ?>
104
+
105
+ <li><a href="<?php echo get_category_link( $child->term_id ); ?>"><?php echo $child->cat_name; ?></a>(子カテゴリアーカイブへのリンク)</li>
106
+
107
+ <?php
108
+
109
+ $args = array(
110
+
111
+ 'posts_per_page' => -1,
112
+
113
+ 'category' => $child->term_id
114
+
115
+ );
116
+
117
+ $myposts = get_posts( $args );
118
+
119
+ //ここから子カテゴリに属する記事のループ
120
+
121
+ if($myposts):
122
+
123
+ foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
124
+
125
+ <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>(子カテゴリ記事)</li>
126
+
127
+ <?php endforeach;
128
+
129
+ wp_reset_postdata();
130
+
131
+ endif;
132
+
133
+ //子カテゴリに属する記事のループここまで
134
+
135
+ ?>
136
+
137
+ <?php endforeach;
138
+
139
+ endif;
140
+
141
+ //子カテゴリのループここまで
142
+
143
+ ?>
144
+
145
+ <?php
146
+
147
+ $args = array(
148
+
149
+ 'posts_per_page' => -1,
150
+
151
+ 'tax_query' => array(
152
+
153
+ array(
154
+
155
+ 'taxonomy' => 'category',
156
+
157
+ 'field' => 'term_id',
158
+
159
+ 'terms' => $category->term_id,
160
+
161
+ 'include_children' => false
162
+
163
+ )
164
+
165
+ )
166
+
167
+ );
168
+
169
+ $myposts = get_posts( $args );
170
+
171
+ //ここから親カテゴリに属する記事のループ
172
+
173
+ if($myposts):
174
+
175
+ foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
176
+
177
+ <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>(親カテゴリ記事)</li>
178
+
179
+ <?php endforeach;
180
+
181
+ wp_reset_postdata();
182
+
183
+ endif;
184
+
185
+ //親カテゴリに属する記事のループここまで
186
+
187
+ ?>
188
+
189
+ </ul>
190
+
191
+ </dd>
192
+
193
+ </dl>
194
+
195
+ <?php endforeach;
196
+
197
+ //親カテゴリのループここまで
198
+
199
+ ?>
200
+
201
+
202
+
203
+ ```