質問編集履歴

1

コード追加

2017/09/27 08:59

投稿

kinakomochi
kinakomochi

スコア24

test CHANGED
File without changes
test CHANGED
@@ -17,3 +17,111 @@
17
17
  ###試したこと
18
18
 
19
19
  カスタム投稿に追加してもらった記事のタイトルをfunctions.phpで一覧取得し、そのショートコードを使用して一覧表示しようと思ったのですが、functions.php内で「echo」を使用するとformの外に一覧表示されてしまい、「return」を使用すると1件しか取得できない問題がおきてしまいます。
20
+
21
+ 下記コードはカテゴリーごとに一覧表示させています。
22
+
23
+
24
+
25
+ ```ここに言語を入力
26
+
27
+ function post_list(){
28
+
29
+ $taxonomyName = "product_category";
30
+
31
+ //親タームだとprentが0なのでこれを指定
32
+
33
+ $args = array(
34
+
35
+ 'parent' => 0
36
+
37
+ );
38
+
39
+ //親を取得
40
+
41
+ $terms = get_terms($taxonomyName,$args);
42
+
43
+ foreach ($terms as $term) {
44
+
45
+ //親のIDを取得できた
46
+
47
+ $parentId = $term->term_id;
48
+
49
+
50
+
51
+ /*ここから親タームのIDがそれぞれ取得できるので、そこから子タームのリストを作る*/
52
+
53
+ //さっきはparentが0だったが、こんかいはprentが親IDの場合の条件
54
+
55
+
56
+
57
+ $childargs = array(
58
+
59
+ 'parent' => $parentId,
60
+
61
+ 'hide_empty' => true//投稿がない場合も隠さずにだす
62
+
63
+ );
64
+
65
+ $childterms = get_terms($taxonomyName,$childargs);
66
+
67
+ echo '<div>';
68
+
69
+
70
+
71
+ foreach ($childterms as $childterm) {
72
+
73
+ $targetSlug = $childterm->slug;
74
+
75
+ echo '<h2 id="'.$childterm->slug.'"><a href="'.get_term_link($childterm->slug, 'product_category').'">'.$childterm->name.'</a></h2>';//子タームの名前
76
+
77
+ //子ターム情報が取得できたので、ここからget_posts用に準備
78
+
79
+ $postargs = array(
80
+
81
+ 'post_type' => 'product',//さっきのbrandsタクソノミーを使ってる“投稿”のポストタイプ
82
+
83
+ 'tax_query' => array(
84
+
85
+ array(
86
+
87
+ 'taxonomy' => $taxonomyName,
88
+
89
+ 'field' => 'slug',//フィールドをslugにしておくterm_idとかでも良いはず
90
+
91
+ 'terms' => $targetSlug//上で準備してある$childterm->slug
92
+
93
+ )
94
+
95
+ )
96
+
97
+ );
98
+
99
+
100
+
101
+ //記事取得
102
+
103
+ $postslist = get_posts( $postargs );
104
+
105
+ foreach ( $postslist as $post ) : setup_postdata( $post );
106
+
107
+ echo get_the_title(); //タイトル
108
+
109
+
110
+
111
+ endforeach;
112
+
113
+ wp_reset_postdata();
114
+
115
+ }
116
+
117
+ echo '</div>';
118
+
119
+ }
120
+
121
+
122
+
123
+ }
124
+
125
+ wpcf7_add_form_tag("list", "post_list");
126
+
127
+ ```