WordPressのクエリで表示の順番を指定する方法

ここでは、WordPressのクエリで表示の順番を指定する方法について説明していきます。

WordPressのクエリで表示の順番を指定するには、パラメータに「order」と「orderby」を用います。
「order」で、昇順か降順かを指定し、「orderby」で、ソートの基準を指定します。

構文

<?php
$args = array(
  'order'  => 'ASC',
  'orderby'   => 'date'
);
$query = new WP_Query($args);
?>

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

表示内容

<?php
  endwhile;
endif;
?>

使用例

<?php
$args = array(
  'order'  => 'ASC',
  'orderby'   => 'date'
);
$query = new WP_Query($args);
?>
<?php
if ($query->have_posts()) :
  while ($query->have_posts()) : $query->the_post();
?>
    <li class="home-main-posts-ul__li">
      <a href="<?php the_permalink(); ?>" target="blank">
        <?php the_title(); ?>
      </a>
      <br>
      <div class="home-main-posts-ul__release-date">
        公開日:<time class="home-main-posts-ul__time"><?php the_date(); ?></time>
      </div>
      <!-- /.home-main-posts-ul__release-date -->
    </li>
<?php
  endwhile;
endif;
?>
  • order:昇順で指定しています。
  • orderby:日付を基準にソートをするよう指定しています。

出力結果

まとめ

このように、クエリのパラメータに「order」「orderby」を指定することで表示順を指定することができます。