サブループを使った時の注意点

サブループ後の記事を出力する際は、get_the_ID()などの()内に、記事を取得した変数を入れる。

OseansWP を使っている時はEditボタンが出るが、そこは最新の投稿しかできなくなる…なんで

<?php
// 1.取得条件を決める(サブループの設定)
$args = array(
    'post_type'      => 'your_post_type', // 投稿タイプを指定
    'posts_per_page' => 5,                // 表示件数
    'tax_query'      => array(            // タクソノミーで絞り込む場合
        array(
            'taxonomy' => 'your_taxonomy',
            'field'    => 'slug',
            'terms'    => 'target-slug',
        ),
    ),
);

// 2.記事データを取得
$custom_posts = get_posts($args);

// 3.記事がある場合のみループを開始
if ($custom_posts) :
    foreach ($custom_posts as $post) : 
        setup_postdata($post); // グローバルな$postをセット
        ?>

        <article>
            <h2><?php the_title(); ?></h2>
            <a href="<?php the_permalink(); ?>">記事を見る</a>
        </article>

    <?php 
    endforeach;

    // 4.サブループを終わらせてメインループの状態に戻す
    wp_reset_postdata(); 

endif;
?>
  • X