• サイトデザイン工事中です。ご意見をお寄せください
  • 赤色のリンクは、まだ日本語Codexに存在しないページ・画像です。英語版と併せてご覧ください。(詳細

このWikiはいつでも誰でも編集できます

テンプレートタグ/query posts

提供:WordPress Codex 日本語版
移動: 案内, 検索

このページ「テンプレートタグ/query posts」は 情報が古くなっている可能性があります。最新版英語)も合わせてご覧ください。最新に更新してくださる協力者を求めています

このページ「テンプレートタグ/query posts」は一部未翻訳です。和訳や日本語情報を加筆してくださる協力者を求めています

目次

説明

query_postsWordPress ループ で表示される投稿を変更するために使います。この関数は URL で使われるのと同じ書式の各種引数(例:p=4 なら 投稿 ID が 4 の投稿のみを表示)を受け取ります。

URL から得られたクエリを変更することはトラブルの元になります。条件分岐タグ のようなページの判定を組み合わせることで、URL を一切変えることなく投稿 の見せ方をカスタマイズすることができます。

よくある利用例:

重要事項

query_posts() 関数はメインの WordPress ループだけを変更するためのものです。新たなループを作るためのものではありません。メインループの他にループが必要な場合は、get_posts() を使ってください。メインループの他で query_posts() を使用すると、メインループが不正な状態になり期待する結果が得られません。

query_posts() 関数はページのメインクエリを上書きし、置き換えます。他の目的で使用しないでください。

query_posts() 関数は新しい WP_Query オブジェクトを作成し、グローバル wp_query 変数に割り当てます。get_posts() 関数は、グローバルエリアをまったく上書きすることなく新しい WP_Query オブジェクトを作成します。

使い方

<?php

// クエリ
query_posts( $args );

// ループ
if ( have_posts() ) : 
  while ( have_posts() ) : 
    the_post();
      ..
  endwhile; 
else:
  ..
endif;

// クエリをリセット
wp_reset_query();

?>

注意事項

query_posts()テンプレート ファイル内で WordPress ループ が始まる前に記述します。wp_query オブジェクトは与えられた引数から新しい SQL クエリを作ります。このとき、WordPress は(ページ番号やカテゴリーのような)URL から得られた引数を無視します。もしその情報が必要なら、query_posts() の引数としてグローバル変数の $query_string を与えます。

例えば、他のクエリ引数に影響を与えずに投稿の表示順序だけを指定したいなら WordPress ループ の前に以下のように記述します:

global $query_string;
query_posts( $query_string . "&order=ASC" );

この形式で query_posts() を使う場合は、二重引用符で囲んだ引数をアンド記号(&)で始めてください。または複数の値の引数を追加する場合、配列にする必要があります。

global $query_string;
parse_str( $query_string, $args );
$args[post_type] = array( 'post', 'video' );
query_posts( $args );

さらに、元のクエリ配列を引数配列に統合することもできます。

global $wp_query;
$args = array_merge( $wp_query->query, array( 'post_type' => 'product' ) );
query_posts( $args );

引数

ここでの記述例がすべてではありません。引数を組み合わせることで、より実用的なクエリが可能になります。

投稿者引数

ある投稿者に関連付けられた投稿を表示する。

Show Posts for one Author

Display posts by author, using author id:

query_posts( 'author=123' );

Display posts by author, using author 'user_nicename':

query_posts( 'author_name=rami' );

Show Posts From Several Authors

Display posts from several specific authors:

query_posts( 'author=2,6,17,38' );

Exclude Posts Belonging to an Author

Display all posts except those from an author by prefixing its id with a '-' (minus) sign:

query_posts( 'author=-123' );

カテゴリー引数

指定したカテゴリーに分類された投稿を表示する。

ひとつのカテゴリーの投稿を表示

ID で指定したカテゴリー(とその子孫カテゴリー)に含まれる投稿のみを表示。

query_posts( 'cat=4' );

カテゴリースラッグで指定したカテゴリー(とその子孫カテゴリー)に含まれる投稿のみを表示。

query_posts( 'category_name=staff' );

複数のカテゴリーの投稿を表示

ID で指定した複数のカテゴリーに含まれる投稿のみを表示。

query_posts( 'cat=2,6,17,38' );

スラッグで指定した複数のカテゴリーに含まれる投稿のみを表示。

query_posts( 'category_name=staff,news' );

指定カテゴリーの投稿を除外

'-'(マイナス)記号を前につけたカテゴリー ID '以外' の投稿を表示。

query_posts( 'cat=-3' );

複数カテゴリーの指定方法

ID で指定した複数のカテゴリーすべてに含まれるカテゴリーを表示。以下はカテゴリー ID 2 と 6 の両方に含まれる投稿を表示。

query_posts( array( 'category__and' => array( 2, 6 ) ) );

カテゴリー ID 2 または 6 に含まれる投稿を表示するには、前述の cat か category__in(こちらは子孫カテゴリーを含みません)を使う。

query_posts( array( 'category__in' => array( 2, 6 ) ) );

また、以下の方法でも複数のカテゴリーを除外できる。

query_posts( array( 'category__not_in' => array( 2, 6 ) ) );

タグ引数

指定したタグがつけられた投稿を表示する。

指定した1つのタグを含む投稿を表示

Display posts that have this tag, using tag slug:

query_posts('tag=cooking');

Display posts that have this tag, using tag id:

query_posts( 'tag_id=13' );


Show Posts From Several Tags

指定したタグのいずれかを含む投稿を表示。

query_posts('tag=bread,baking');

指定した3つのタグすべてを含む投稿を表示。

query_posts('tag=bread+baking+recipe');

複数タグの指定方法

タグ ID 37 と 47 の両方を含む投稿を表示。

query_posts( array( 'tag__and' => array( 37, 47 ) ) );

タグ ID 37 または 47 のいずれかを含む投稿を表示するには、前述の tagtag__in を使う。

query_posts( array( 'tag__in' => array( 37, 47 ) ) );

タグ ID 37 と 47 のいずれも含まない投稿を表示。

query_posts( array( 'tag__not_in' => array( 37, 47 ) ) );

tag_slug__intag_slug__and はタグスラッグを指定する他は上記と同様です。

Ryan's discussion of Tag intersections and unions も参照してください。

タクソノミー引数

特定のタクソノミーに関連付けられた投稿を表示。

シンプルタクソノミークエリ

'people' カスタムタクソノミーで 'bob' というスラッグのタグがつけられた投稿を表示。

query_posts( array( 'people' => 'bob', 'posts_per_page' => 10 ) );

複数のタクソノミー処理 (バージョン 3.1 以降)

複数のカスタムタクソノミーの投稿を表示。

$args = array(
	'tax_query' => array(
		'relation' => 'AND',
		array(
			'taxonomy' => 'movie_janner',
			'field' => 'slug',
			'terms' => array( 'action', 'commedy' ),
		),
		array(
			'taxonomy' => 'actor',
			'field' => 'id',
			'terms' => array( 103, 115, 206 ),
			'operator' => 'NOT IN',
		)
	)
)
query_posts( $args );

投稿者引数

指定した ID や名前の投稿者による投稿を表示する。

注意: author_nameuser_nicename フィールドの値を指定します。author には ID を指定します。

author=1 のすべての 固定ページ をタイトル順, 先頭固定表示無しで表示

query_posts('caller_get_posts=1&author=1&post_type=page&post_status=publish&orderby=title&order=ASC');

投稿・固定ページ引数

ブログ投稿や固定ページに関連付けられた post を表示。

ID を指定して投稿・固定ページを表示

特定の ID の投稿を表示。

query_posts( 'p=7' );

特定の ID の固定ページを表示。

query_posts( 'page_id=7' );

スラッグを指定して投稿・固定ページを表示

Display post by his slug:

query_posts( 'name=about-my-life' );

Display page by his slug:

query_posts( 'pagename=contact' );

Show Child Posts/Pages

Display child pages using the slug of the parent and the child page, separated by a slash:

query_posts( 'pagename=parent_slug/child_slug' );

Display child pages using parent page ID:

query_posts( 'post_parent=93' );

Multiple Posts/Pages Handling

Display only the specify posts:

query_posts( array( 'post__in' => array( 2, 5, 12, 14, 20 ) ) );

Display all posts but NOT the specify ones:

query_posts( array( 'post__not_in' => array( 2, 5, 12, 14, 20 ) ) );

Note: you cannot combine 'post__in' and 'post__not_in' in the same query.

投稿タイプを指定して投稿を表示

ページのみを表示。

query_posts( 'post_type=page' );

'any' 投稿タイプを表示 (履歴以外のすべてのタイプを取得)。

query_posts( 'post_type=any' );

カスタム投稿タイプを含む複数の投稿タイプを表示。

query_posts( array( 'post_type' => array( 'post', 'page', 'movie', 'book' ) ) );

状態を指定して投稿を表示

下書きのみを表示。

query_posts( 'post_status=draft' );

複数の投稿状態を指定して表示。

query_posts( array( 'post_status' => array( 'pending', 'draft', 'future' ) ) );

ページ送り引数

Pagination Note: You should set get_query_var( 'page' ); if you want your query to work with pagination. Since Wordpress 3.0.2, you do get_query_var( 'page' ) instead of get_query_var( 'paged' ). The pagination parameter 'paged' for query_posts() remains the same.

Show x Posts per page

Display 3 posts per page:

query_posts( 'posts_per_page=3' );

Show All Post

Display all posts in one page:

query_posts( 'posts_per_page=-1' );

Display all posts by disabling pagination:

query_posts( 'nopaging=true' );

Show Posts from page x

Display posts from page number 6:

query_posts( 'paged=6' );

Show Posts from Current Page

Display posts from current page:

$page = get_query_var( 'page' );
query_posts( 'paged=$page' );

オフセット引数

表示される投稿の先頭から指定した件数をスキップします。

以下は、最新の投稿(1件)に続く5件の投稿を表示。

query_posts('posts_per_page=5&offset=1');

並び順・並べ替え引数

取得した投稿を並べ替える。

Show Posts sorted by Title, Descending order

Display posts sorted by post title in a descending order:

query_posts( 'orderby=title&order=DESC' );

Show Random Post

Display one random post:

query_posts( 'orderby=rand&posts_per_page=1' );

Show Popular Posts

Display posts ordered by comment count:

query_posts( 'orderby=comment_count&order=DESC' );

先頭固定投稿引数

Sticky Post Parameters

Show sticky post or ignore them.

Show Sticky Posts

Display just the first sticky post:

$sticky = get_option( 'sticky_posts' );
query_posts( 'p=' . $sticky[0] );

Display just the first sticky post, if none return the last post published:

$args = array(
	'posts_per_page' => 1,
	'post__in'  => get_option( 'sticky_posts' ),
	'ignore_sticky_posts' => 1
);
query_posts( $args );

Display just the first sticky post, if none return nothing:

$sticky = get_option( 'sticky_posts' );
$args = array(
	'posts_per_page' => 1,
	'post__in'  => $sticky,
	'ignore_sticky_posts' => 1
);
query_posts( $args );
if ( $sticky[0] ) {
	// insert here your stuff...
}

Don't Show Sticky Posts

Exclude all sticky posts from the query:

query_posts( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );

Exclude sticky posts from a category. Return ALL posts within the category, but don't show sticky posts at the top. The 'sticky posts' will still show in their natural position (e.g. by date):

query_posts( 'ignore_sticky_posts=1&posts_per_page=3&cat=6' );

Exclude sticky posts from a category. Return posts within the category, but exclude sticky posts completely, and adhere to paging rules:

$paged = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;
$sticky = get_option( 'sticky_posts' );
$args = array(
	'cat' => 3,
	'ignore_sticky_posts' => 1,
	'post__not_in' => $sticky,
	'paged' => $paged
);
query_posts( $args );

日時引数

指定した日時の間に投稿された投稿を表示。

今日の投稿を表示

$today = getdate();
query_posts( 'year=' . $today["year"] . '&monthnum=' . $today["mon"] . '&day=' . $today["mday"] );

現在の週の投稿のみを表示

$week = date('W'); $year = date('Y'); query_posts( 'year=' . $year . '&w=' . $week );

12月20日の投稿を表示

query_posts( 'monthnum=12&day=20' );

Note: The queries above return posts for a specific date period in history, i.e. "Posts from X year, X month, X day". They are unable to fetch posts from a timespan relative to the present, so queries like "Posts from the last 30 days" or "Posts from the last year" are not possible with a basic query, and require use of the posts_where filter to be completed. The examples below use the posts_where filter, and should be modifyable for most time-relative queries.

2009年3月15日の投稿を表示

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts for March 1 to March 15, 2010
	$where .= " AND post_date >= '2010-03-01' AND post_date < '2010-03-16'";
	return $where;
}
add_filter( 'posts_where', 'filter_where' );

query_posts( $query_string );

最近30日間の投稿を表示

<pre>
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts in the last 30 days
	$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
	return $where;
}
add_filter( 'posts_where', 'filter_where' );

query_posts( $query_string );

30〜60日前の投稿を表示

<pre>
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts  30 to 60 days old
	$where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'";
	return $where;
}
add_filter( 'posts_where', 'filter_where' );

query_posts( $query_string );

カスタムフィールド引数

カスタムフィールドのキーまたは値を元に投稿を表示。

キーが 'color' で値が 'blue' のカスタムフィールドを持つ投稿を表示。

query_posts( 'meta_key=color&meta_value=blue' );

値は問わず、キーが 'color' のカスタムフィールドを持つ投稿を表示。

query_posts( 'meta_key=color' );

キーは問わず、値が 'blue' のカスタムフィールドを持つ投稿を表示。

query_posts( 'meta_value=color' );

キーは問わず、値が 'green' のカスタムフィールドを持つ固定ページを表示。

query_posts( 'post_type=page&meta_value=green' );

Returns posts with a custom field value of zero (0), regardless of the custom field key:

query_posts( 'meta_value'='_wp_zero_value' );

キーが 'color' で値が 'blue' でないカスタムフィールドを持つ投稿と固定ページの両方を表示。

query_posts( 'post_type=any&meta_key=color&meta_compare=!=&meta_value=blue' );

キーが 'miles' で値が 22 以下のカスタムフィールドを持つ投稿を表示。注:値は数値ではなく文字列として扱われているため「99」は「100」より大きくなります。

query_posts( 'meta_key=miles&meta_compare=<=&meta_value=22' );

引数の組み合わせ

引数はアンド記号(&)を使って複数組み合わせて指定することができます:

query_posts( 'cat=3&year=2004' );

「最新の投稿」ページで、カテゴリー ID が 13 かつ今月の投稿を表示する:

if (is_home()) {
query_posts( $query_string . '&cat=13&monthnum=' . date( 'n', current_time( 'timestamp' ) ) );
}

バージョン 2.3 では、以下の組み合わせは カテゴリー ID 1 と 3 に含まれる投稿を2件、タイトルの降順で表示。

query_posts( array( 'category__and' => array(1,3), 'posts_per_page' => 2, 'orderby' => 'title', 'order' => 'DESC' ) );

バージョン 2.3バージョン 2.5 では、カテゴリー ID が 1 で "apples" を含む投稿を表示することが期待される。

query_posts( 'cat=1&tag=apples' );

バグ:カテゴリーとタグを同時に指定する場合は「+」で同じタグを2つ指定してください。参照 Ticket #5433

query_posts( 'cat=1&tag=apples+apples' );

注意:'cat=1&tag=apples+oranges' は期待する結果にはなりません。

コード記述例

「最新の投稿」ページから指定カテゴリーを除く

index.php ファイルに以下のコードを書くと、カテゴリー ID が 3 以外の 投稿を表示。

<?php
   if ( is_home() ) {
      query_posts( 'cat=-3' );
   }
?>

複数のカテゴリー ID を指定できる(バージョン 2.1.2 で検証済)。

<?php
   if ( is_home() ) {
      query_posts( 'cat=-1,-2,-3' );
   }
?>

特定の投稿を表示

特定の投稿を表示。

<?php
query_posts( 'p=5' );  
?>

続きを読む を表示したい場合は、グローバル変数 $more を 0 にします。

<?php
// 投稿 ID が 5 の投稿を表示する
query_posts( 'p=5' );

// 投稿の始めの部分のみ表示するため $more を 0 にする
global $more;
$more = 0;

// ループ
while (have_posts()) : the_post();
  the_content( 'Read the full post »' );
endwhile;
?>

2008年5月に投稿された、カテゴリー ID 1 と 3 の投稿タイトルを1ページに5件ずつ表示する:

<?php if (have_posts()) :  query_posts('posts_per_page=5&cat=1,3&monthnum=5&year=2008');  ?>
  <?php while (have_posts()) : the_post(); ?>
    <h2><?php the_title(); ?></h2>
<?php endwhile; endif; ?>

カテゴリー ID 2 と 6 のいずれにも含まれないすべての投稿のタイトルをリストとして表示する:

<?php if (have_posts()) :  query_posts(array('category__not_in' => array(2,6))); ?>
<ul>
 <?php while (have_posts()) : the_post(); ?>
    <li><?php the_title(); ?></li>
<?php endwhile; endif; ?>
</ul>

query_posts に変数を与える

query_posts に変数を与える方法は2通りあります。どちらを使用してもかまいません。WordPress ループ の前に記述してください:

記述例 1

この例は、query_posts を実行する前にクエリ文字列を連結します。まず変数に値を代入し、変数と文字列を結合して、実行します。ここではカテゴリー ID を変数で与えることにします。

 $categoryvariable = $cat;  // 現在のカテゴリー ID を変数に代入
 $query = 'cat=' . $categoryvariable . '&orderby=date&order=ASC'; // クエリを連結
 query_posts( $query ); // run the query // クエリを実行

記述例 2

次の例では、二重引用符を使って PHP に式を評価させます。まず、現在の年・月を表示し、query_posts で公開日が現在の年・月に該当する投稿を表示します。投稿の並び順は日付の昇順で、公開日の古い順に表示します。

$current_year = date('Y');
$current_month = date('m');
query_posts( "cat=22&year=$current_year&monthnum=$current_month&order=ASC" );

記述例 3

この例では、ページングを使ってすべての投稿を表示する場合を説明します。デフォルトの $query_string を使って query_posts ですべての投稿を表示させることができます。posts_per_page の値には -1 か各ページに表示したい投稿の数を指定します。後者の場合には posts_nav_link() でページを移動する手段を提供しましょう。

query_posts( $query_string . '&posts_per_page=-1' );

記述例 4

$query_string 変数を使わずに、引数を配列に入れる方法もあります。例えば、記述例 2 のクエリは以下のようになります:

$args = array(
	'cat'      => 22,
	'year'     => $current_year,
	'monthnum' => $current_month,
	'order'    => 'ASC'
);
query_posts( $args );

この方法は、変数ごとに1行ずつ記述すると読み易くなります。

オリジナルクエリの保持(ページングなど)

デフォルトでは query_posts を実行すると、引数で指定した変数を除きページング,カテゴリー,日付などの現在のページのクエリ変数はすべて上書きされます。

オリジナルのクエリを保持したい場合は、query_poats の引数にオリジナルクエリの配列をマージしてください:

global $wp_query;
query_posts(
	array_merge(
		array( 'cat' => 1 ),
		$wp_query->query
	)
);


使い方のヒント

管理画面の 設定 > 表示設定 にある "1ページに表示する最大投稿数" パラメータで通常の表示件数を指定できます。これを変更するには 'posts_per_page' 引数を使います:

query_posts( 'category_name=The Category Name&posts_per_page=-1' );  // 指定カテゴリーに含まれるすべての投稿を表示

The "Syndication feeds show the most recent" or "posts per rss" parameters in Settings > Reading will overwrite any posts_per_page parameter in a query used in a feed. To overcome use (for example in a a custom ics feed, where all matching posts are required), use the "posts_limit" filter as follows:

if ( isset ( $query->query_vars['feed'] ) and ( $query->query_vars['feed'] == 'ics' ) )
	add_filter( 'post_limits', 'no_limits_for_feed' );

function no_limits_for_feed( $limits ) {
	return '';
}

リソース

最新英語版: WordPress Codex » Template Tags/query posts最新版との差分

関連

テンプレート:Query Tags

pt-br:Referência de Função/query posts
個人用ツール
名前空間
変種
操作
このサイトについて
特集
サーバ別情報
リファレンス
ドキュメント整備
ツールボックス
他の言語