2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WordPressのカスタム投稿タイプの2ページ目が404になる

Posted at

はじめに

なんかWordPressで2ページ目が404になる現象ってよくあって、検索すれば大量に記事が出てきますね。
しかしどれもピンとこず、しかも解決できない...
と思っていたところに、いい解決策に出会ったので、ご紹介します。でも元記事は忘れましたごめんなさい。

今回は、カスタム投稿を取得するときにposts_per_pageを指定してハマったんですよね。
この対応方法は、標準の投稿も使うし、カスタム投稿タイプも複数使うし、かつ、それぞれ1ページに表示する件数が違うという場合に使えます!
というか、そういう場合にハマります!
(1ページに表示する件数とは、管理画面 > 設定 > 表示設定 > 1ページに表示する最大投稿数のことです)

簡単にいうと、pre_get_postsを使います。
ではさっそく見ていきましょう!
(なお、プログラムは記事用に書き換えて動作確認してませんので...)

プログラムです!

functions.php

<?php
//カスタム投稿タイプのページネーションの件数を設定する(定数にしておくことをおすすめします)
const CUSTOM_POSTS_PER_PAGE = 8;

function change_posts_per_page($query) {
    if ( is_admin() || !$query->is_main_query() ) {
        return;
    }

    //カスタム投稿タイプの一覧、カスタムタクソノミーなどposts_per_pageを書き換える条件を書きます
    if ( $query->is_archive( 'works' ) || is_tax('works_category') || is_tax('works_tag')) {
        $query->set( 'posts_per_page', CUSTOM_POSTS_PER_PAGE );
    }
}
add_action( 'pre_get_posts', 'change_posts_per_page' );

archive-works.php

アーカイブページなので、本来であれば、while ( have_posts() ) : the_post();な感じで取得できるのですが、今回は他に検索条件を追加するという要件があったので、new WP_Query()を使用しております。

//現在のページ番号を取得
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;

$args = [
    'post_type' => 'works',
    'posts_per_page' => CUSTOM_POSTS_PER_PAGE,
    'paged' => $paged,
];

$the_query = new WP_Query( $args );

while($the_query->have_posts() ): $the_query->the_post();
    //ループの中身
endwhile; wp_reset_postdata();

//ページネーション
$pagenateArgs = [
    'total' => $the_query->max_num_pages,
];
echo paginate_links($pagenateArgs);

最後に

WordPress歴も長くなってくると、ページャーも余裕だわと思っていたら、ハマるときもありますね。
プラグインなんか使わなくても...と思いますが、プログラムに詳しい人がいないと使わざるを得ないときもあるんかな...

関数リファレンス/paginate links

2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?