WordPress初心者に、functions.phpの使い方についてお聞かせください。
たとえばこのようなコードをsingle.phpに書く場合、
php
1<ul class="custom-tags"> 2<?php 3if ($genres = get_the_terms($post->ID, 'custom-tag')) { 4 foreach ( $genres as $genre ) { 5 echo '<li>'.esc_html($genre->name).'</li>'; 6 } 7}?> 8</ul>
上のように8行程度であっても、かつ、使うシーンが一度だけであっても、single.phpでなくfunctions.phpに次のように書いて、
php
1<?php 2function custom_tags(){ 3 if ($genres = get_the_terms($post->ID, 'custom-tag')) { 4 foreach ( $genres as $genre ) { 5 echo '<li>'.esc_html($genre->name).'</li>'; 6 } 7 } 8} 9?>
そしてsingle.phpでは<?php custom_tags; ?>
として1行に収める方が適切でしょうか?
あと、functions.phpですが、上のように「➀functions.phpでechoにする」のと、「➁functions.phpではreturnにして、single.phpでechoにする」のと、それぞれ適切なケースを知りたいです。
初歩的な質問で恐縮ですが、どうぞ宜しくお願い致します。
回答2件
あなたの回答
tips
プレビュー