WordPressでタイトル順に投稿を並べ替える方法
ここでは、WordPressでWordPressでタイトル順に投稿を並べ替える方法について説明していきます。
構文
<?php
$args = array(
'orderby' => 'title',
'order' => 'ASC',
);
$query = new WP_Query($args);
?>
- orderbyでは、タイトル順に並べ替えることを指定しています・
- orderでは、昇順に並べ替えることを指定しています。(デフォルトは’DESC’)
使用例
<?php
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => 6
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
get_template_part('template-parts/card');
endwhile;
endif;
?>
</div>
<!-- /.home-main-posts__cards cards -->
ここで用いられいているget_template_part(‘template-parts/card’)の中身は以下の通りです。
<a href="<?php the_permalink(); ?>" class="cards__item card">
<figure class="card__img-wrapper">
<?php if (has_post_thumbnail()) : ?>
<?php the_post_thumbnail(); ?>
<?php else : ?>
<?php echo wp_get_attachment_image(574); ?>
<?php endif; ?>
</figure>
<div class="card__body">
<h3 class="card__title">
<?php the_title(); ?>
</h3>
<p class="card__text">
<?php the_excerpt(); ?>
</p>
</div>
<!-- /.card__body -->
</a>
出力結果

まとめ
上記のように、WP_Query()の引数に、「’orderby’ => ‘title’」、「’order’ => 降順or昇順」とすることで、タイトル順に投稿を表示させることができます。