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

回答編集履歴

1

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

2018/10/03 10:59

投稿

marlboro_tata
marlboro_tata

スコア525

answer CHANGED
@@ -18,4 +18,85 @@
18
18
 
19
19
  ```
20
20
 
21
- 今のコードには、「親カテゴリに属する子カテゴリを取得してループする」という部分がまるっと抜けています。(時間があれば具体的なコードを追記します)
21
+ 今のコードには、「親カテゴリに属する子カテゴリを取得してループする」という部分がまるっと抜けています。
22
+
23
+ サンプルのコードは以下の通りです。WP_Queryではなく、get_posts()を使いました。
24
+ 親カテゴリの記事一覧を取得するときに、やはり、子カテゴリの記事も合わせて取ってきてしまうので、
25
+ 'tax_query' で 'include_children' => false を追記することで、親カテゴリ直下の記事のみ取り出せました。
26
+
27
+ ```PHP
28
+ <?php
29
+ $args = array(
30
+ 'parent' => 0,
31
+ 'hide_empty' => 0
32
+ );
33
+ $categories = get_categories($args);
34
+ //以下から親カテゴリのループ
35
+ foreach($categories as $category) :
36
+ ?>
37
+ <dl>
38
+ <dt>
39
+ <a href="<?php echo get_category_link( $category->term_id ); ?>"><?php echo $category->cat_name; ?></a>(親カテゴリアーカイブへのリンク)
40
+ </dt>
41
+ <dd>
42
+ <ul>
43
+ <?php
44
+ $args = array(
45
+ 'parent' => $category->term_id,
46
+ 'hide_empty' => 0
47
+ );
48
+ $children = get_categories($args);
49
+ //以下から子カテゴリのループ
50
+ if($children):
51
+ foreach($children as $child) :
52
+ ?>
53
+ <li><a href="<?php echo get_category_link( $child->term_id ); ?>"><?php echo $child->cat_name; ?></a>(子カテゴリアーカイブへのリンク)</li>
54
+ <?php
55
+ $args = array(
56
+ 'posts_per_page' => -1,
57
+ 'category' => $child->term_id
58
+ );
59
+ $myposts = get_posts( $args );
60
+ //ここから子カテゴリに属する記事のループ
61
+ if($myposts):
62
+ foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
63
+ <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>(子カテゴリ記事)</li>
64
+ <?php endforeach;
65
+ wp_reset_postdata();
66
+ endif;
67
+ //子カテゴリに属する記事のループここまで
68
+ ?>
69
+ <?php endforeach;
70
+ endif;
71
+ //子カテゴリのループここまで
72
+ ?>
73
+ <?php
74
+ $args = array(
75
+ 'posts_per_page' => -1,
76
+ 'tax_query' => array(
77
+ array(
78
+ 'taxonomy' => 'category',
79
+ 'field' => 'term_id',
80
+ 'terms' => $category->term_id,
81
+ 'include_children' => false
82
+ )
83
+ )
84
+ );
85
+ $myposts = get_posts( $args );
86
+ //ここから親カテゴリに属する記事のループ
87
+ if($myposts):
88
+ foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
89
+ <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>(親カテゴリ記事)</li>
90
+ <?php endforeach;
91
+ wp_reset_postdata();
92
+ endif;
93
+ //親カテゴリに属する記事のループここまで
94
+ ?>
95
+ </ul>
96
+ </dd>
97
+ </dl>
98
+ <?php endforeach;
99
+ //親カテゴリのループここまで
100
+ ?>
101
+
102
+ ```