mk-webwork codenote

トップページなどに、記事の最新◯件を表示する。

標準ループとは別の条件でループ処理を実行するには、WP_Queryを使用する。
参考:

https://wpdocs.osdn.jp/Äb0関数リファレンスÄb0/WP_QueryÄb0

https://developer.wordpress.org/reference/classes/wp_query/Äb0

ul、olの中に記述。

<ol class="section-news__container">
      <?php $args_news= array(
          'post_type' => 'news',
          'posts_per_page' => 3,
          );
           $the_query_news= new WP_Query( $args_news); ?>
        <?php if( $the_query_news->have_posts() ) : while( $the_query_news->have_posts() ) : $the_query_news->the_post(); ?>
        <-- ループさせる記事1個の内容 -->
     <li class="section-news__content"><a href="<?php the_permalink(); ?>">
            <div class="section-news__thumbnail">
            <img class="section-news__thumbnail-image" src="<?php the_post_thumbnail_url('large'); ?>" alt="<?php the_title(); ?>"></div>
            <h3 class="section-news__title"><?php the_title(); ?></h3>
            </a>
        </li>
     <-- 記事ここまで -->
      <?php endwhile; wp_reset_postdata(); endif; ?>
    </ol>

↓WP_Queryの開始。別ループさせる記事のすぐ前に記述。

<?php $args_news= array(
          'post_type' => 'news',
          'posts_per_page' => 3,
          );
           $the_query_news= new WP_Query( $args_news); ?>
        <?php if( $the_query_news->have_posts() ) : while( $the_query_news->have_posts() ) : $the_query_news->the_post(); ?>

↓投稿タイプに紐付けする。

'post_type' => 'news',

↓表示する記事の数を指定する。

'posts_per_page' => 3,

↓WP_Queryの終了。ループさせる記事のすぐ後に記述。

<?php endwhile; wp_reset_postdata(); endif; ?>
← もどる