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

質問編集履歴

1

変更したコードを追記しました。

2020/12/04 06:04

投稿

kii.32
kii.32

スコア67

title CHANGED
File without changes
body CHANGED
@@ -144,7 +144,103 @@
144
144
  }
145
145
  ```
146
146
 
147
+ ### 追記12.4
148
+ 回答にて出力バッファをご教授いただき、下記サイトを参考に実装をしてみました。
149
+ [wordpress投稿記事でPHPを使う方法](https://webmemo.tokyo/articles/make-wp-shortcode/#pos4-1)
147
150
 
151
+ すると、出力自体はできているのですが、
152
+ ループ中のカスタムフィールド 部分の出力がされず、
153
+ どこが悪いのでしょうか。。。
154
+
155
+
156
+ 出力ショートコード↓
157
+ ```出力ショートコード
158
+ [get_tag_query result_meta_key=hogehoge meta_value=hoge result_post_type=news result_post_num=8]
159
+ ```
160
+
161
+ functions.php↓
162
+ ```functions.php
163
+ // Include ShortCode
164
+ require(dirname(__FILE__) . '/template-parts/shortcode.php');
165
+ ```
166
+
167
+ shotcode.php↓
168
+ ```shotcode.php
169
+ <?php
170
+ function get_tag_query_func($atts)
171
+ {
172
+ // 引数処理
173
+ extract(shortcode_atts(array(
174
+ 'result_post_type' => '',
175
+ 'result_post_num' => '-1',
176
+ 'result_meta_key' => '',
177
+ 'result_meta_value' => '',
178
+ ), $atts, 'get_tag_query'));
179
+
180
+
181
+ ob_start();
182
+ // 投稿取得処理
183
+ $args = array(
184
+ 'post_type' => $result_post_type,
185
+ 'posts_per_page' => $result_post_num,
186
+ 'meta_key' => $result_meta_key, //カスタムフィールドのキー
187
+ 'meta_value' => $result_meta_value, //カスタムフィールドの値
188
+ 'meta_compare' => 'LIKE', //'meta_value'のテスト演算子
189
+ );
190
+ $tagPosts = get_posts($args);
191
+ ?>
192
+ <?php if ($tagPosts) : foreach ($tagPosts as $post) : setup_postdata($post); ?>
193
+
194
+ <a class="post_item" href="<?php the_permalink(); ?>">
195
+ <?php if (post_custom('news_pic')) : // 入力がある場合
196
+ ?>
197
+ <figure class="news_pic">
198
+ <img src="<?php the_field('news_pic'); ?>" alt="">
199
+ </figure>
200
+ <?php else : // 入力がない場合
201
+ ?>
202
+ <figure class="news_pic">
203
+ <img src="<?php echo get_template_directory_uri(); ?>/assets/img/common/noimage.png" alt="">
204
+ </figure>
205
+
206
+ <?php endif; ?>
207
+ <div class="news_info">
208
+ <h3 class="news_title">
209
+ <?php
210
+ if (mb_strlen($post->post_title, 'UTF-8') > 21) {
211
+ $title = mb_substr($post->post_title, 0, 21, 'UTF-8');
212
+ echo $title . '……';
213
+ } else {
214
+ echo $post->post_title;
215
+ }
216
+ ?>
217
+ </h3>
218
+ <p class="news_area"><?php the_field('news_area'); ?></p>
219
+ <ul class="news_cat">
220
+ <?php
221
+ $obj = get_field_object('news_cat');
222
+ $news_cat = $obj['value'];
223
+ foreach ($news_cat as $news_cat_name) {
224
+ echo '<li>', $news_cat_name, '</li>';
225
+ }
226
+ ?>
227
+ </ul>
228
+ </div>
229
+ </a>
230
+ <?php endforeach;
231
+ endif; ?>
232
+ <?php wp_reset_postdata(); ?>
233
+ <?php
234
+
235
+ $output = ob_get_clean();
236
+ return $output;
237
+ }
238
+
239
+ add_shortcode('get_tag_query', 'get_tag_query_func');
240
+
241
+ ?>
242
+ ```
243
+
148
244
  phpの初学者でして、
149
245
  調べてもなかなか解決ができず、質問をさせていいただきました。
150
246