ki-hi-ro.com WEB制作フリーランスエンジニア
  • Service
    • WEBサイトの更新サポート
    • 新規サイトコーディング
  • Introduce
    • メッセージ
    • 自宅兼事務所
    • Twitter
  • Blog
    • 技術ブログ
    • 学習ブログ
    • 雑記ブログ
  • Others
    • スケジュールのお知らせ
    • お問い合わせ
    • WEBに関する無料相談
  • Top
  • Service
  • Introduce
  • Blog
  • Contact

出力する記事を指定する

ブログシステムのWordPressでは、出力する記事を指定することができます。

今回は、customというカスタム投稿タイプの記事を、記事数の指定無しで、投稿日の降順に出力させる場合のPHPの記述方法について書いていきます。

コード

<?php
$custom_posts = get_posts(array(
 'post_type' => 'custom',
 'posts_per_page' => -1,
 'orderby' => 'date',
 'order' => 'DESC'
));
global $post;
if($custom_posts): foreach($custom_posts as $post): setup_postdata($post); 
?>

 <?php the_title(); ?>

<?php endforeach; wp_reset_postdata(); endif; ?>

結論のコードです。
これで、customというカスタム投稿タイプの記事のタイトルが、記事数の指定無しで、投稿日の降順に表示されます。

順番に解説していきます。

customというカスタム投稿タイプの記事のタイトル

<?php
$custom_posts = get_posts(array(
 'post_type' => 'custom',
 'posts_per_page' => -1,
 'orderby' => 'date',
 'order' => 'DESC'
));
global $post;
if($custom_posts): foreach($custom_posts as $post): setup_postdata($post); 
?>

 <?php the_title(); ?>

<?php endforeach; wp_reset_postdata(); endif; ?>

‘post_type’ => ‘custom’ で、customというカスタム投稿タイプを指定しています。

一般的には、’post_type’ => ‘カスタム投稿タイプ名’ で、カスタム投稿タイプを指定できます。

記事数の指定無しで

<?php
$custom_posts = get_posts(array(
 'post_type' => 'custom',
 'posts_per_page' => -1,
 'orderby' => 'date',
 'order' => 'DESC'
));
global $post;
if($custom_posts): foreach($custom_posts as $post): setup_postdata($post); 
?>

 <?php the_title(); ?>

<?php endforeach; wp_reset_postdata(); endif; ?>

‘posts_per_page’ => -1 で、記事数の制限を無くしています。

一般的には、’posts_per_page’ => [表示させたい記事数] で、記事数を制限することができます。

日付の降順に

<?php
$custom_posts = get_posts(array(
 'post_type' => 'custom',
 'posts_per_page' => -1,
 'orderby' => 'date',
 'order' => 'DESC'
));
global $post;
if($custom_posts): foreach($custom_posts as $post): setup_postdata($post); 
?>

 <?php the_title(); ?>

<?php endforeach; wp_reset_postdata(); endif; ?>

‘orderby’ => ‘date’ で、投稿日を並べ替え条件の基準にすることができ、
‘order’ => ‘DESC’ で、降順に並べ替えることができます。

一般的には、’orderby’ => ‘条件’ で、条件を並べ替えの条件にすることができ、
‘order’ => ‘ASC か DESC’ で、昇順か降順で並べ替えることができます。

並べ替えの条件

今回の’orderby’ => ‘date’ (日付で並べ替える) の他に、以下のように条件を指定することができます。

  • ‘orderby’ => ‘modified’ ・・・ 更新日で並べ替える
  • ‘orderby’ => ‘name’・・・記事スラッグで並べ替える
  • ‘orderby’ => ‘rand’・・・ランダムに並べ替える

タイトルを出力する

<?php
$custom_posts = get_posts(array(
 'post_type' => 'custom',
 'posts_per_page' => -1,
 'orderby' => 'date',
 'order' => 'DESC'
));
global $post;
if($custom_posts): foreach($custom_posts as $post): setup_postdata($post); 
?>

 <?php the_title(); ?>

<?php endforeach; wp_reset_postdata(); endif; ?>

<?php the_title(); ?> の部分で、条件にあった記事のタイトルを出力しています。

関連記事

2022.04.30 WordPress 記事内リンクを別タブで開くようにする方法
2022.03.25 WordPress カスタムフィールドの出力方法

サービス一覧

  • WEBサイトの更新サポート
  • 新規サイトコーディング

自己紹介

  • メッセージ
  • 自宅兼事務所
  • Twitter

ブログ

  • 技術ブログ
  • 学習ブログ
  • 雑記ブログ

その他

  • スケジュールのお知らせ
  • お問い合わせ