Blog

【WordPress】query_postsを使わずに一覧の件数を指定する方法

2016/07/18

カスタム投稿 Wordpress

備忘録です。

参考サイト
WordPressでコンテンツごとにアーカイブページの表示件数を変更するベストな方法

通常であれば下記のように指定をします。
archive-**.php

<?php
query_posts('&posts_per_page=10');
if (have_posts()) : while (have_posts()) : the_post(); ← ループスタート
?>

しかし、query_postsは最近推奨されていないため、functionsで表示件数の指定をします。

functions.php

function change_posts_per_page($query) {
    if ( is_admin() || ! $query->is_main_query() )
        return;
 
    if ( $query->is_archive() ) { /* アーカイブページの時に表示件数を5件にセット */
        $query->set( 'posts_per_page', '5' );
    }
}
add_action( 'pre_get_posts', 'change_posts_per_page' );

いろいろな条件分岐のパターン
functions.php

function change_posts_per_page($query) {
    if ( is_admin() || ! $query->is_main_query() )
        return;
 
    /* アーカイブページの時に表示件数を10件にセット */
    if ( $query->is_archive() ) {
        $query->set( 'posts_per_page', '10' );
    }

    /* ポストアーカイブの時に表示件数を30件にセット */
    if ( $query->is_post_type_archive($post_types) ) {
        $query->set( 'posts_per_page', '30' );
    }

    /* 検索ページの時に表示件数を20件にセット */
    if ( $query->is_search() ) {
        $query->set( 'posts_per_page', '20' );
    }

    /* タクソノミー「hoge」の時に表示件数を20件にセット */
    if ( $query->is_tax('hoge') ) {
        $query->set( 'posts_per_page', '20' );
    }
}
add_action( 'pre_get_posts', 'change_posts_per_page' );

is_post_type_archive($post_types)は()にpost-typeを指定します。
例:is_post_type_archive('news')
これで特定のカスタム投稿の件数を指定できます。

その他条件分岐は下記を参考にしてください。
条件分岐タグ





カテゴリー

月間アーカイブ

MORE

ミュージシャンズ・プラザ

神社仏閣ホームーページ制作

ホームページ制作問合せ