ワードプレスのquery_postsは非推奨となっています。
理由はいろいろあるらしいですが、pre_get_postsをレギュレーションとしている会社も増えてきましたね。
■ループ文(テンプレート側)
1 2 3 4 5 6 7 |
<?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php // 処理 ?> <?php endwhile; ?> <?php endif; ?> |
■functions.php ↓大体下記見たらわかると思う↓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// pre_get_posts function change_posts_per_page($query) { if ( is_admin() || ! $query->is_main_query() ){ return; } // トップページ if ($query->is_home()) { // 処理内容 $query->set( 'post_type',array( 'post','aaa' ) ); $query->set( 'posts_per_page', '3' ); return; } // カスタム投稿タイプアーカイブページ if ($query->is_post_type_archive('event')) { // 処理内容 $query->set( 'posts_per_page', '10' ); return; } // アーカイブページ if ($query->is_archive()) { // 処理内容 $query->set( 'posts_per_page', '10' ); return; } } add_action( 'pre_get_posts', 'change_posts_per_page' ); |
つまり、今までテンプレートにクエリを書き込んでいたのをfunctions.phpに変更しちゃおうっていう話です。これによりデータベースの負担も軽減するとかしないとか。
ページャーとかも今まで通りのものが使えました。
■各ページ別に読み込めます
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
<?php function custo_main_query($query) { if (is_admin() || !$query->is_main_query()) { return; } // トップページ if ($query->is_home()) { // 処理内容 return; } // 固定ページ if ($query->is_page()) { // 処理内容 return; } // アーカイブページ if ($query->is_archive()) { // 処理内容 return; } // カスタム投稿タイプアーカイブページ if ($query->is_post_type_archive('post_type')) { // 処理内容 return; } // 日付アーカイブページ if ($query->is_date()) { // 処理内容 return; } // 年別アーカイブページ if ($query->is_year()) { // 処理内容 return; } // 月別アーカイブページ if ($query->is_month()) { // 処理内容 return; } // 制作者アーカイブページ if ($query->is_author()) { // 処理内容 return; } // カテゴリーページ if ($query->is_category()) { // 処理内容 return; } // タグページ if ($query->is_tag()) { // 処理内容 return; } // タクソノミーページ if ($query->is_tax()) { // 処理内容 return; } //詳細ページ if ($query->is_single()) { // 処理内容 return; } // 検索結果ページ if ($query->is_search()) { // 処理内容 return; } // フィードページ if ($query->is_feed()) { // 処理内容 return; } // 404ページ if ($query->is_404()) { // 処理内容 return; } } add_action('pre_get_posts', 'custom_main_query'); |
■参考サイト
https://dev-memo.com/php/pre-get-posts
https://qiita.com/_ruka_/items/e14280d34eddf49efad1
https://www.tam-tam.co.jp/tipsnote/cms/post9420.html
↓いろんなクエリの例も書いてある↓
http://emiac-works.com/coding/pre-get-posts-code-snipet/