🏡まったのブログ

WordPressのループを逆順に出力する

WordPressのループ(the_post() の部分)で逆順に出力したい場面。Post Types Order プラグインを使用して並べ換える方法もあるが、Bogoプラグインなどで多言語化していたりするとページャー部分がおかしくなるので、プログラム側で制御したい。

$args = array(
  'post_type' => 'post_type_name',
  'order' => 'ASC'
);
$the_query = new WP_Query( $args );


if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) :
        $the_query->the_post();
        // 出力内容

    endwhile;
    wp_reset_postdata();
endif;

$wp_queryを使っている場合

グローバル変数$wp_queryを利用したアーカイブページなどでは、先の形に書き換える必要がある。このケースで$wp_queryで該当の投稿タイプの一覧だけ出力できるのは、ファイル名がarchive-post_type.phpの形になっているため自動で'post_type' => 'post_type_name'が適用されているのだと思う。

global $wp_query;

if ( have_posts() ) :
       while ( have_posts() ) :
             the_post();
        // 出力内容

    endwhile;
endif;