WordPressで出力する記事を指定する方法

はじめに

ブログシステムの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(); ?> の部分で、条件にあった記事のタイトルを出力しています。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です