ループ(カスタム投稿)
ループ(基本)
<?php while ( have_posts() ) : the_post(); ?>
<?php endwhile;?>
ループ(親子)
「親(カテゴリー)」の中に「子(そのカテゴリーに属する記事)」を並べる「入れ子構造(親子ループ)」のテンプレートです。
<? php
$terms = get_terms('custom-category');
foreach($terms as $term): ?>
< h2 > <? php echo $term - > name; ?> < /h2>
<? php
$infoPosts = get_posts(array(
'post_type' => 'custom',
'numberposts' => -1,
'industries-category' => $term - > slug,
));
foreach($infoPosts as $post): ?>
< a href = "<?php the_permalink(); ?>" >
< h3 > <? php the_title(); ?> < /h3>
< /a>
<? php endforeach; ?>
<? php endforeach; ?>
詳しい説明
<?php
/* --- ① カテゴリーの情報をまとめて取ってくる --- */
// 'custom-category'(タクソノミー)に登録されている
// ターム(個別のカテゴリー名)をすべて取得して $terms という変数に保存します。
$terms = get_terms('custom-category');
/* --- ② 【外側のループ】カテゴリーの数だけ繰り返し処理を開始 --- */
// 取得したカテゴリーを一つずつ取り出し、変数 $term に入れてループを回します。
foreach($terms as $term): ?>
<!-- ③ カテゴリー名を画面に表示 -->
<!-- $term->name は、カテゴリーの名前(例:実績紹介など)を表示します。 -->
<h2><?php echo $term->name; ?></h2>
<?php
/* --- ④ 【中身の準備】そのカテゴリーに紐づく記事を探す --- */
// get_posts を使って、特定の条件に合う記事(投稿)を検索します。
$infoPosts = get_posts(array(
'post_type' => 'custom', // カスタム投稿タイプ「custom」から探す
'numberposts' => -1, // 記事は全部取得する
'industries-category' => $term->slug, // 現在ループ中のカテゴリーに属する記事だけに絞り込む
));
/* --- ⑤ 【内側のループ】見つかった記事の数だけ繰り返し処理を開始 --- */
// ④で取得した記事リスト($infoPosts)から、1つずつ $post に入れてループを回します。
foreach($infoPosts as $post): ?>
<!-- ⑥ 記事へのリンクとタイトルを表示 -->
<!-- the_permalink() はその記事のURL、the_title() はタイトルを出力します。 -->
<a href="<?php the_permalink(); ?>">
<h3><?php the_title(); ?></h3>
</a>
<?php
/* --- ⑦ 内側のループ(記事の表示)が終了 --- */
// そのカテゴリーに属する記事をすべて出し終えたら、このループを抜けます。
endforeach; ?>
<?php
/* --- ⑧ 外側のループ(カテゴリーの表示)が終了 --- */
// 次のカテゴリーがあれば ② に戻り、なければすべての処理が完了します。
endforeach; ?>