get_posts

Sponsored Link

複数のループを作成するためのシンプルな関数です。最新記事や条件に一致する投稿のリストを取得します。

パラメータはget_pagesに似ていますが、いくつかの異なる名前を持っているか、わずかに異なる値を取得することに注意してください。

Sponsored Link

This is a simple function for creating multiple loops. It retrieves a list of latest posts or posts matching criteria.

Note that although the parameters are similar to get_pages, several have different names or take slightly different values.

get_postsのテンプレートタグ使用方法

<?php $posts_array = get_posts( $args ); ?>

デフォルトの使用方法

<?php $args = array(
    'numberposts'     => 5,
    'offset'          => 0,
    'category'        => ,
    'orderby'         => 'post_date',
    'order'           => 'DESC',
    'include'         => ,
    'exclude'         => ,
    'meta_key'        => ,
    'meta_value'      => ,
    'post_type'       => 'post',
    'post_mime_type'  => ,
    'post_parent'     => ,
    'post_status'     => 'publish' ); ?>

get_postsのパラメーター

get_posts() は、記事を取得するためにWP_Queryクラスを利用します。この関数が受け取るパラメーターの一覧についてはWP_Queryドキュメンテーションのパラメーターセクションを参照してください。

注:get_postsはデフォルトとして’suppress_filters’=> trueを使用し、get_postsがデフォルトでフィルターを適用している間、WPMLのようにクエリ修正プラグインを使用しているときに混乱することができます。

get_posts() makes use of the WP_Query class to fetch posts. See the parameters section of the WP_Query documentation for a list of parameters that this function accepts.

Note: get_posts uses ‘suppress_filters’ => true as default, while query_posts() applies filters by default, this can be confusing when using query-modifying plugins, like WPML.

戻り値

(array)
投稿オブジェクトのリスト。get_post()の戻り値をチェックしてください。

(array)
List of post objects. Check get_post() return values.

オフセット付きの記事一覧

あなたのブログにフロントページ上にちょうど1つの投稿を表示するように設定し、カテゴリーID1の前の5つの投稿へのリンクを一覧表示したい場合、これを使用することができます。

If you have your blog configured to show just one post on the front page, but also want to list links to the previous five posts in category ID 1, you can use this:

<ul>
<?php
global $post;
$args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :	setup_postdata($post); ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>

注:オフセットを使用すると、上記のクエリはそこに1つの投稿よりカテゴリー上のみで使用すべきなので、何も出力されないでしょう。

Note: With use of the offset, the above query should be used only on a category that has more than one post in it, otherwise there’ll be no output.

オフセットと記事リストの後にリセットする方法

foreachを追加する前に持っていた投稿が、ループ後に必要である場合、これを使用することができます。

If you need after the loop, the post you had before joining the foreach, you can use this:

<ul>
<?php
global $post;
$tmp_post = $post;
$args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
</ul> 

全ての記事データにアクセスする方法

いくつかの投稿に関連するデータは、例えば投稿内容が the_content()あるいは数値IDを介して、デフォルトでget_postsに利用できません。これは、その引数として$post配列と一緒に、内部関数のsetup_postdata()を呼び出すことで解決されます。

Some post-related data is not available to get_posts by default, such as post content through the_content(), or the numeric ID. This is resolved by calling an internal function setup_postdata(), with the $post array as its argument:

<?php
$args = array( 'numberposts' => 3 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>
	<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
	<?php the_content(); ?>
<?php endforeach; ?>

setup_postdata()、または実際に任意の投稿固有のデータ(投稿テーブル内に保持されているデータ)を呼び出さずに投稿IDまたは内容にアクセスするには、COLUMNがデータ用のテーブル列名である、$post->COLUMNを使用することができます。post->IDがIDを保持するので、$post->post_contentは内容などです。ページ上でこのデータをPHPのechoコマンドを使用して表示したり印刷するためには、下記のようになります。

To access a post’s ID or content without calling setup_postdata(), or in fact any post-specific data (data retained in the posts table), you can use $post->COLUMN, where COLUMN is the table column name for the data. So $post->ID holds the ID, $post->post_content the content, and so on. To display or print this data on your page use the PHP echo command, like so:

<?php echo $post->ID; ?>

タイトル順で最新記事を表示する方法

昇順にアルファベット順に並び替えた最後の10記事を表示するために、以下投稿日時、タイトルと抜粋を表示します。

To show the last ten posts sorted alphabetically in ascending order, the following will display their post date, title and excerpt:

<?php
$args = array( 'numberposts' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ($postslist as $post) :  setup_postdata($post); ?> 
	<div>
		<?php the_date(); ?>
		<br />
		<?php the_title(); ?>   
		<?php the_excerpt(); ?>
	</div>
<?php endforeach; ?>

投稿をランダムに表示する方法

従順なパラメータ値に対するMySQL RAND() 関数を使用することによってランダムに選ばれた5つの投稿リストを表示します。

Display a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value:

<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>

全ての添付ファイルを表示する方法

テンプレート内で任意のループの外で使用します。

Do this outside any Loops in your template.

<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null ); 
$attachments = get_posts( $args );
if ($attachments) {
	foreach ( $attachments as $post ) {
		setup_postdata($post);
		the_title();
		the_attachment_link($post->ID, false);
		the_excerpt();
	}
}
?>

現在の記事に添付ファイルを表示する方法

このThe_Loop($post->IDが利用可能です)内で使用します。

Do this inside The_Loop (where $post->ID is available).

<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ); 
$attachments = get_posts($args);
if ($attachments) {
	foreach ( $attachments as $attachment ) {
		echo apply_filters( 'the_title' , $attachment->post_title );
		the_attachment_link( $attachment->ID , false );
	}
}
?>

スラッグで投稿を取得する方法

投稿スラッグによる投稿IDを取得することができます。caller_get_posts引数は、このカスタムクエリーから固定投稿を除外します。

Allows you to get a post ID by post slug. The caller_get_posts argument excludes sticky posts from this custom query.

< ?php $the_slug = 'my_slag'; $args=array( 'name' => $the_slug,
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘showposts’ => 1,
‘caller_get_posts’=> 1
);
$my_posts = get_posts($args);
if( $my_posts ) {
echo ‘ID on the first post found ‘.$my_posts[0]->ID;
}
?>

カスタム投稿カテゴリー(タクソノミー)

カスタム投稿タイプからカテゴリーを指定する場合は、’category’ を使用する代わりに'{your_custom_post_type}_category’を使用します。例えば、”ドッグフード”というカスタム投稿タイプがあり、”ブランド”カテゴリーから投稿のみ表示したい場合は、下記のコードを使用します。

If specifying a category from a custom post type then instead of using ‘category’ you would use ‘{your_custom_post_type}_category’. For instance, if you had a custom post type called “dogfood” and wanted to only show posts from the category “brand” you would use the below code.

<?php
$args = array(
   'numberposts' => 8,
   'orderby' => 'rand',
   'post_type' => 'dogfood',
   'dogfood_category' => 'brand',
   'post_status' => 'publish'
);
$show_brands = get_posts ( $args );
?>

パラメーター: WordPress 2.6+

パラメーターの”WordPress 2.5 より以下”の下記のように加えて、get_posts()もパラメーターを取得する事ができ、query_posts() は両方の関数以来、現在内部的に同じデータベースのクエリーコードを使用する事が出来ます。

注:バージョン2.6は順序のオプションの数を変更しました。post_で始まるテーブルフィールドは、もはや名前の一部ではありません。例えば、post_titleは現在のタイトルで、post_dateは現在の日付です。

注:バージョン3.0から、ページIDの配列もパラメーターをインクルード&除外するために使用する事が出来ます。

In addition to the parameters listed below under “WordPress 2.5 And Older”, get_posts() can also take the parameters that query_posts() can since both functions now use the same database query code internally.

Note: Version 2.6 changed a number of the orderby options. Table fields that begin with post_ no longer have that part of the name. For example, post_title is now title and post_date is now date.

Note: Beginning with Version 3.0, an array of Page ID also can be used for the include and exclude parameters.

パラメーター: WordPress 2.5 より古い場合

$numberposts

(integer) (optional) 記事の数字を返します。0に設定された場合、1ページ当たりの記事の最大数を使用します。-1に設定された場合、制限を削除します。

(integer) (optional) Number of posts to return. Set to 0 to use the max number of posts per page. Set to -1 to remove the limit.

Default: 5

$offset

(integer) (optional) 最新の記事からオフセットします。

(integer) (optional) Offset from latest post.

Default: 0

$category

(integer) (optional) このカテゴリーIDからの記事のみ表示します。負数 (3よりはむしろ-3)でカテゴリーIDを作成した場合、カテゴリIDが一致しない結果を表示するでしょう。複数のカテゴリーIDは、コンマでカテゴリーIDを区切られる事によって指定する事が出来ますが、IDの配列は動作しません。

(integer) (optional) Only show posts from this category ID. Making the category ID negative (-3 rather than 3) will show results not matching that category ID. Multiple category IDs can be specified by separating the category IDs with commas – but an array of IDs does not work.

Default: None

$category_name

(string) (optional) このカテゴリー名あるいはカテゴリースラッグからの記事のみ表示します。

(string) (optional) Only show posts from this category name or category slug.

Default: None

$tag

(string) (optional) タグスラッグの記事のみ表示します。コンマによって区切られた複数のタグスラッグを指定する場合、全ての結果は一致している任意のタグが返されるでしょう。スペースによって区切られた複数のタグスラッグが指定する場合、結果は全ての指定されたタグスラッグがマッチするでしょう。

(string) (optional) Only show posts with this tag slug. If you specify multiple tag slugs separated by commas, all results matching any tag will be returned. If you specify multiple tag slugs separated by spaces, the results will match all the specified tag slugs.

Default: None

$orderby

(string) (optional) 1つの様々な値(スペースによって区切られた)によって記事を並び替えて、インクルードします:

(string) (optional) Sort posts by one of various values (separated by space), including:

  • ‘author’ – 数字の著者IDによって並び替える。
  • ‘category’ – 数字のカテゴリーIDによって並び替える。
  • ‘content’ – コンテンツによって並び替える。
  • ‘date’ – 作成日によって並び替える。
  • ‘ID’ – 数時の記事IDによって並び替える。
  • ‘menu_order’ – メニュー順によって並び替える。ページと添付ファイルのみで有効です。
  • ‘mime_type’ – MIMEタイプによって並べ替える。添付ファイルのみで有効です。
  • ‘modified’ – 最終更新日によって並び替える。
  • ‘name’ – 使い残りのよって並び替える。
  • ‘parent’ – 親IDによって並び替える。
  • ‘password’ – パスワードによって並び替える。
  • ‘rand’ – ランダムに並び替えた結果。
  • ‘status’ – ステータスによって並び替える。
  • ‘title’ – タイトルによって並び替える。
  • ‘type’ – タイプによって並び替える。
  • ‘author’ – Sort by the numeric author IDs.
  • ‘category’ – Sort by the numeric category IDs.
  • ‘content’ – Sort by content.
  • ‘date’ – Sort by creation date.
  • ‘ID’ – Sort by numeric post ID.
  • ‘menu_order’ – Sort by the menu order. Only useful with pages and attachments.
  • ‘mime_type’ – Sort by MIME type. Only useful with attachments.
  • ‘modified’ – Sort by last modified date.
  • ‘name’ – Sort by stub.
  • ‘parent’ – Sort by parent ID.
  • ‘password’ – Sort by password.
  • ‘rand’ – Randomly sort results.
  • ‘status’ – Sort by status.
  • ‘title’ – Sort by title.
  • ‘type’ – Sort by type.

注釈

:

IDとランダムによって並び替える事は、バージョン2.5で始まっているもののみ利用可能です。

  • Sorting by ID and rand is only available starting with Version 2.5.

Default: post_date

$order

(string) (optional) $orderbyで並び替える方法です。有効な値:

(string) (optional) How to sort $orderby. Valid values:

  • ‘ASC’ – 昇順 (lowest to highest).
  • ‘DESC’ – 降順 (highest to lowest).

Default: DESC

$include

(string) (optional) コンマあるいはスペースによって区切られた、表示したい記事のIDです。次の値は、表示しているこれらの6つの記事に動作するでしょう。

(string) (optional) The IDs of the posts you want to show, separated by commas and/or spaces. The following value would work in showing these six posts:

  • ‘45,63, 78 94 ,128 , 140’

注:このパラメーターはnumberposts, offset, category, exclude, meta_key, meta_value,そしてpost_parent parametersを上書きして使用します。

Note: Using this parameter will override the numberposts, offset, category, exclude, meta_key, meta_value, and post_parent parameters.

Default: None

$exclude

(string) (optional) カンマかスペース($includeパラメーターを参照)によって区切られた、除外したい全ての記事のIDです。

(string) (optional) The IDs of any posts you want to exclude, separated by commas and/or spaces (see $include parameter).

Default: None

$meta_key and $meta_value

このキーと値を持つメタ(カスタム)フィールドを含む記事のみ表示します。両方のパラメーターは定義する必要もありますし、どちらも動作します。

(string) (optional) Only show posts that contain a meta (custom) field with this key and value. Both parameters must be defined, or neither will work.

Default: None

$post_type

(string) (optional) 表示するための記事のタイプです。使用可能なオプションがあります:

(string) (optional) The type of post to show. Available options are:

  • post – デフォルト
  • page
  • attachment
  • any – 全ての記事タイプ

Default: post

$post_status

(string) (optional) 特定のステータスである記事を表示します。複数ステータスはカンマで区切って指定する事が出来ます。使用可能なオプションがあります:

(string) (optional) Show posts with a particular status. Multiple statuses can be given, separated with a comma. Available options are:

  • publish – デフォルト
  • private
  • draft
  • future
  • inherit – $post_typeが添付ファイルに設定されている場合は、デフォルトです。Default if $post_type is set to attachment
  • (blank) – すべてのステータス

Default: publish

$post_parent

(integer) (optional) このIDの記事の子のみ表示します。

(integer) (optional) Show only the children of the post with this ID

Default: None

$nopaging

(boolean) (optional) ページングを有効または無効にします。ページングが向こうの場合、$numberpostsオプションは無視されます。

(boolean) (optional) Enable or disable paging. If paging is disabled, the $numberposts option is ignored.

Default: None

変更ログ

Since: 1.2.0

ソースファイル

get_posts()は、wp-includes/post.php内に位置しています。

get_posts() is located in wp-includes/post.php.

関連テンプレートタグ

get_posts, query_posts, rewind_posts, wp_reset_query

Sponsored Link