LoginSignup
1
1

More than 1 year has passed since last update.

WordPressループ処理、件数やカテゴリー指定

Last updated at Posted at 2021-01-19

ループ処理の基本的な書き方と、カテゴリーや件数での条件を指定した書き方をまとめました

ループ処理の基本的な書き方

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

 <!-- 記事のループ処理 -->

<?php endwhile; ?>
<?php else : ?>

 <!-- 記事が無い場合 -->

<?php endif; ?>

ループ処理の中身の一例

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <span><?php the_time('Y/m/d'); ?></span>
    <?php endwhile; ?>
<?php else : ?>
    <p>記事がありません</p>
<?php endif; ?>

この書き方では以下のようになります

記事がある場合

  • タイトルをaタグで囲んで表示、リンクは投稿先へ
  • spanタグで日付を年/月/日で表示
  • この処理を記事がある分だけ繰り返す
  • ループ終わり

記事が無い場合

  • 「記事がありません」という文字列をpタグで囲んで表示
  • ループ終わり

更に最初に少し書き加えると、条件を指定した表示ができます。

カテゴリーを指定

'cat=○○'この部分に表示させたいカテゴリのIDを入れる

<?php query_posts('cat=1'); ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 <!-- 記事のループ処理 -->
<?php endwhile; ?>
<?php else : ?>
 <!-- 記事が無い場合 -->
<?php endif; ?>

複数のカテゴリを指定する場合はカンマで区切る

<?php query_posts('cat=1,3,5'); ?>

指定のカテゴリを表示しない場合

<?php query_posts('cat=-1'); ?>

表示数を指定

'posts_per_page=〇〇'この部分に表示数を入れる

<?php query_posts('posts_per_page=10'); ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 <!-- 記事のループ処理 -->
<?php endwhile; ?>
<?php else : ?>
 <!-- 記事が無い場合 -->
<?php endif; ?>

指定のカテゴリの表示数を指定

<?php query_posts('cat=1&posts_per_page=10'); ?>

まとめ

規模の小さいコーポレートサイトやブログの更新システムは、この書き方で十分まかなえるかと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1