query_posts

Sponsored Link

query_posts() は、ループ内でどの記事を表示するかを制御するために使用する事が出来ます。URL(例.p=4はID番号4の記事のみを表示)に使用される同じ形式で様々なパラメーターを引き受けます。

なぜ慎重にURLの取得から作成されたクエリーを変更している全ての問題を経ているのか?ページロジック(条件タグの様に)と組み合わせることによって、エントリーしたブログの提示をカスタマイズする事が出来ます。–全ての任意URLを変更せずに。

一般的な用途に可能性があります:

Sponsored Link

query_posts() can be used to control which posts show up in The Loop. It accepts a variety of parameters in the same format as used in your URL (e.g. p=4 to show only post of ID number 4).

Why go through all the trouble of changing the query that was meticulously created from your given URL? You can customize the presentation of your blog entries by combining it with page logic (like the Conditional Tags) — all without changing any of the URLs.

Common uses might be to:

  • ホームページにシングル記事のみ表示します(シングルページは設定>Readingを介してする事ができます)。
  • 特定の期間から全ての記事を表示します。
  • フロントページに最新記事(のみ)を表示します。
  • 記事がを順序付けた方法を変更します。
  • 1つのカテゴリーのみから記事を表示します。
  • 1つまたは複数カテゴリーを除外します。
  • Display only a single post on your homepage (a single Page can be done via Settings -> Reading).
  • Show all posts from a particular time period.
  • Show the latest post (only) on the front page.
  • Change how posts are ordered.
  • Show posts from only one category.
  • Exclude one or more categories.

重要な注意

query_posts関数は、メインページのループのみで変更するために使用する事を目的としています。ページ上の2次ループを作成する手段として目的としているのではありません。
メインの1つの外部の個別ループを作成したい場合は、個別のWP_Queryオブジェクトを作成すべきで、それらを代わりに使用します。メインの1つ以外にループでのquery_postsの使用は、メインループが間違った結果に終わり、恐らく予期していなかった事を表示します。

query_posts関数は、ページのメインクエリーを無効にして置き換えます。
健全さを保ち、他の目的に使用しないでください。

The query_posts function is intended to be used to modify the main page Loop only. It is not intended as a means to create secondary Loops on the page. If you want to create separate Loops outside of the main one, you should create separate WP_Query objects and use those instead. Use of query_posts on Loops other than the main one can result in your main Loop becoming incorrect and possibly displaying things that you were not expecting.

The query_posts function overrides and replaces the main query for the page. To save your sanity, do not use it for any other purpose.

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

<?php

//The Query
query_posts('posts_per_page=5');

//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
 ..
endwhile; else:
 ..
endif;

//Reset Query
wp_reset_query();

?>

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

ループで始まる前のテンプレートファイルの1つには、query_posts()を呼び出します。wp_queryオブジェクトは、パラメーターを使用する新しいSQLクエリーを生成します。これを行う時は、WordPressはURLを介して受信する他のパラメーターを無視します(ページ数あるいはカテゴリーなど)。その情報を保持したい場合は、query_posts()を呼び出しで、$query_string グローバル変数を使用する事ができます。

例えば、ループの前に次のように置くことができる、クエリー文字列の残りの部分に影響を与えないように記事の表示順序を設定します。

Place a call to query_posts() in one of your Template files before The Loop begins. The wp_query object will generate a new SQL query using your parameters. When you do this, WordPress ignores the other parameters it receives via the URL (such as page number or category). If you want to preserve that information, you can use the $query_string global variable in the call to query_posts().

For example, to set the display order of the posts without affecting the rest of the query string, you could place the following before The Loop:

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

この方法でquery_postsを使用する時、引数の引用部分は、アンパサンド(&)で始まらなければなりません。

When using query_posts in this way, the quoted portion of the argument must begin with an ampersand (&).

query_postsのパラメーター

これは、完全なリストはまだありません。独自のクエリーを設定するとより一般的なことが可能ないくつかの表示をしなければならない。

This is not an exhaustive list yet. It is meant to show some of the more common things possible with setting your own queries.

カテゴリーのパラメーター

特定のカテゴリーに属している記事の方法です。

Show posts only belonging to certain categories.

  • cat -カテゴリーIDを使用しなければなりません。
  • category_name
  • category__and -カテゴリーIDを使用しなければなりません。
  • category__in – カテゴリーIDを使用しなければなりません。
  • category__not_in – カテゴリーIDを使用しなければなりません。
  • cat – must use cat ids
  • category_name
  • category__and – must use cat ids
  • category__in – must use cat ids
  • category__not_in – must use cat ids

IDによって1つのカテゴリーを表示する方法

1つのカテゴリーID(そのカテゴリーの全ての子)のみから記事を表示します。

Display posts from only one category ID (and any children of that category):

query_posts('cat=4');

名前によって1つのカテゴリーを表示する方法

名前によって1つのカテゴリーのみから記事を表示します。

Display posts from only one category by name:

query_posts('category_name=Staff Home');

IDによっていくつかのカテゴリーを表示します。

いくつか特定のカテゴリーIDから記事を表示します。

Display posts from several specific category IDs:

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

1つのカテゴリーのみ属している記事を除外する方法

‘-‘(マイナス)記号でそのIDを付与することによって、カテゴリーから除外する全ての記事を表示します。

Show all posts except those from a category by prefixing its ID with a ‘-‘ (minus) sign.

query_posts('cat=-3');

これは、カテゴリー3に属するすべての記事を除外します。

This excludes any post that belongs to category 3.

複数のカテゴリーの処理する方法

複数のカテゴリーにある記事を表示します。これは、カテゴリー2と6の両方の記事を表示します。

Display posts that are in multiple categories. This shows posts that are in both categories 2 and 6:

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

上記のようにカテゴリー使用する事ができます、あるいは、category__in(それらのカテゴリーのいづれの子から記事を表示しないことに注意してください)を使用する事によって、2または6のいづれかのカテゴリーから記事を表示します。

To display posts from either category 2 OR 6, you could use cat as mentioned above, or by using category__in (note this does not show posts from any children of these categories):

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

この方法を複数カテゴリーも除外する事ができます。:

You can also exclude multiple categories this way:

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

タグのパラメーター

特定のタグに関連付けられた記事を表示します。

Show posts associated with certain tags.

  • tag
  • tag_id – タグIDを使用しなければなりません。
  • tag__and – タグIDを使用しなければなりません。
  • tag__in – タグIDを使用しなければなりません。
  • tag__not_in – タグIDを使用しなければなりません。
  • tag_slug__and
  • tag_slug__in
  • tag
  • tag_id – must use tag ids
  • tag__and – must use tag ids
  • tag__in – must use tag ids
  • tag__not_in – must use tag ids
  • tag_slug__and
  • tag_slug__in

1つのタグの記事を取得する方法

query_posts('tag=cooking');

それらのタグにいずれかを持っている記事を取得する方法

query_posts('tag=bread,baking');

それらのタグの3つの全ての記事を取得する方法

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

複数のタグの処理する方法

タグID37とタグID47の両方のタグ付けられた記事を表示します。

Display posts that are tagged with both tag id 37 and tag id 47:

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

上記のようにタグを使用することができる事で、タグID37か47からいづれかの記事を表示します。あるいはtag__inを使うことによって明確に特定されます。

To display posts from either tag id 37 or 47, you could use tag as mentioned above, or explicitly specify by using tag__in:

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

任意の2つのタグID37と47を持たない記事を表示します:

Display posts that do not have any of the two tag ids 37 and 47:

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

tag_slug__inとtag_slug__andは、ほぼ同じ動作をし、タグスラッグと競争させることを除外します。

The tag_slug__in and tag_slug__and behave much the same, except match against the tag’s slug.

タグの共通部分や結合についてはライアンの議論を参照してください。

Also see Ryan’s discussion of Tag intersections and unions.

著者パラメーター

著者の記事も制限する事ができます。

You can also restrict the posts by author.

  • author=3
  • author=-3 – 著者ID3の記事を除外します。
  • author_name=Harriet
  • author=3
  • author=-3 – exclude author id 3 posts
  • author_name=Harriet

注:author_nameは、user_nicenameフィールドで動作するのと同時に、著者は著者IDフィールドで動作します。

Note: author_name operates on the user_nicename field, whilst author operates on the author id field.

トップに追加した固定記事がないと、タイトル順に、author=1に対して全てのページを表示する方法

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

記事とページのパラメーター

シングル記事やページを取得します。

Retrieve a single post or page.

  • ‘p’ => 27 – 記事を表示するために記事IDを使用します。
  • ‘name’ => ‘about-my-life’ – この投稿スラッグを持つ特定の記事のためのクエリーです。
  • ‘page_id’ => 7 – まさにページID7のクエリーです。
  • ‘pagename’ => ‘about’ – これはページのタイトルではなく、ページのパスであることに注意してください。
  • ‘posts_per_page’ => 1 – 3つの記事を表示するために、’posts_per_page’ => 3を使用します。全ての記事を表示するために’posts_per_page’ => -1を使用します。
  • ‘showposts’ => 1 – 3つの記事を表示するために’showposts’ => 3 を使います。全ての記事を表示するためには、’showposts’ => -1 を使用します。posts_per_pageに賛成して非推奨です。
  • ‘post__in’ => array(5,12,2,14,7) – 含む場合は、投稿IDが取得するために指定する事ができます。
  • ‘post__not_in’ => array(6,2,8) – 投稿IDを取得しないために指定する事ができます。
  • ‘post_type’ => ‘page’ – ページを返す;投稿の値がデフォルトです;任意の添付ファイル、ページ、記事、またはリビジョンになることができます。任意のリビジョンを除くタイプを任意で取得します。また、カスタムポストタイプ(例:映画など)を指定する事ができます。
  • ‘post_status’ => ‘publish’ -作品の公開を返します。また、ペンディング、ドラフト、将来、プライベート、ゴミ箱を使う事ができます。継承については、get_childrenを参照してください。ゴミ箱ステータスはバージョン2.9で追加されました。
  • ‘post_parent’ => 93 – ページ93の子ページを返します。
  • ‘p’ => 27 – use the post ID to show that post
  • ‘name’ => ‘about-my-life’ – query for a particular post that has this Post Slug
  • ‘page_id’ => 7 – query for just Page ID 7
  • ‘pagename’ => ‘about’ – note that this is not the page’s title, but the page’s path
  • ‘posts_per_page’ => 1 – use ‘posts_per_page’ => 3 to show 3 posts. Use ‘posts_per_page’ => -1 to show all posts
  • ‘showposts’ => 1 – use ‘showposts’ => 3 to show 3 posts. Use ‘showposts’ => -1 to show all posts. Deprecated in favor of posts_per_page
  • ‘post__in’ => array(5,12,2,14,7) – inclusion, lets you specify the post IDs to retrieve
  • ‘post__not_in’ => array(6,2,8) – exclusion, lets you specify the post IDs NOT to retrieve
  • ‘post_type’ => ‘page’ – returns Pages; defaults to value of post; can be any, attachment, page, post, or revision. any retrieves any type except revisions. Also can designate custom post types (e.g. movies).
  • ‘post_status’ => ‘publish’ – returns publish works. Also could use pending, draft, future, private, trash. For inherit see get_children. Status of trash added with Version 2.9.
  • ‘post_parent’ => 93 – return just the child Pages of Page 93.

To return both posts and custom post type movie

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

固定記事のパラメーター

固定記事はWordPressのバージョン2.7で最初に利用できるようになりました。caller_get_posts=1パラメーターで除外しない限り、クエリー内の他の記事の前に表示した固定で設定された記事です。

Sticky posts first became available with WordPress Version 2.7. Posts that are set as Sticky will be displayed before other posts in a query, unless excluded with the caller_get_posts=1 parameter.

  • array(‘post__in’=>get_option(‘sticky_posts’)) – 全ての固定記事の配列を返します。
  • caller_get_posts=1 – 固定記事を除外するには、返された記事の冒頭に含まれているが、固定記事は未だに返された記事のリストの自然な順序で返されるでしょう。
  • array(‘post__in’=>get_option(‘sticky_posts’)) – returns array of all sticky posts
  • caller_get_posts=1 – To exclude sticky posts being included at the beginning of posts returned, but the sticky post will still be returned in the natural order of that list of posts returned.

まさに最初の固定記事を返すには:

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

あるいは、

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

注:2番目のメソッドは、より近い固定記事のみ返します;固定記事がない場合、公開された最終記事を返します。

Note: the second method returns only the more recent sticky post; if there are not sticky posts, it returns the last post published.

まさに最初の固定記事または何かを返すには:

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

クエリーから全ての固定記事を除外するには:

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

カテゴリーと全ての記事を返しますが、トップに固定記事を表示しません。’固定記事’はまだ自然な位置(例.日付など)に表示されます:

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

カテゴリーのために記事を返しますが、ページングのルールに従って、完全に固定記事を除外されます。

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

時間のパラメーター

一定期間に属する記事を取得します。

Retrieve posts belonging to a certain time period.

  • hour= – 時 (0~23)
  • minute= – 分 (0~60)
  • second= – 秒 (0~60)
  • day= – 月日 (1~31)
  • monthnum= – 月数 (1~12)
  • year= – 4桁の年(例えば. 2009)
  • w= –
    その年の週とMySQL WEEK command Mode=1を使用します(0~53)。
  • hour= – hour (from 0 to 23)
  • minute= – minute (from 0 to 60)
  • second= – second (0 to 60)
  • day= – day of the month (from 1 to 31)
  • monthnum= – month number (from 1 to 12)
  • year= – 4 digit year (e.g. 2009)
  • w= – week of the year (from 0 to 53) and uses the MySQL WEEK command Mode=1.

まさに現在の日付の記事を返します:

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

まさに現在の週の記事を返します:

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

12月20日付の記事を返します:

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

2009年、5月1日から5月15日に渡っている記事を返します:

<?php
//based on Austin Matzko's code from wp-hackers email list
  function filter_where($where = '') {
//posts for March 1 to March 15, 2009
$where .= " AND post_date >= '2009-03-01' AND post_date<'2009-03-16'";
return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>

過去30日間からの記事を返します:

<?php
//based on Austin Matzko's code from wp-hackers email list
  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日齢の記事を返します:

<?php
//based on Austin Matzko's code from wp-hackers email list
  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);
?>

ページめくりのパラメーター

  • nopaging=true – ページめくりを無効にし、全ての記事を表示します。
  • posts_per_page=10 – 1ページあたりに表示する記事数
  • paged=2 – “古いエントリー”へのリンクを使用する時に、ちょうど2ページだけで通常現れるであろう記事を表示します。クエリーをページめくりで動作したい場合は、このget_query_var( ‘paged’ )の設定をすべきです。
  • order=ASC – 年代順に記事を表示します。DESCは逆順序(デフォルト)に表示します。
  • nopaging=true – will disable pagination, displaying all posts
  • posts_per_page=10 – number of posts to show per page
  • paged=2 – show the posts that would normally show up just on page 2 when using the “Older Entries” link. You should set this to get_query_var( ‘paged’ ) if you want your query to work with pagination.
  • order=ASC – show posts in chronological order, DESC to show in reverse order (the default)

オフセットパラメーター

オフセットパラメーターを使用するクエリーを介す事によって、通常収集されるであろう1つ以上の初期記事を移すあるいは引き渡す事ができます。

You can displace or pass over one or more initial posts which would normally be collected by your query through the use of the offset parameter.

以下は、次の最近の(1)5つの記事を表示します:

The following will display the 5 posts which follow the most recent (1):

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

順序のパラメーター

並べ替えは、このフィールドによって記事を取得します。

Sort retrieved posts by this field.

  • orderby=author
  • orderby=date
  • orderby=title
  • orderby=modified
  • orderby=menu_order ページ(ページ編集・属性ボックス内のフィールド順序付けられた)そして添付ファイル(メディアの挿入/アップロード・ギャラリーダイアログ内の整数フィールド)で最も頻繁に使用されますが、異なるmenu_order値(それらは全て0がデフォルト)を持つ任意の記事タイプに使用する事ができます。
  • orderby=parent
  • orderby=ID
  • orderby=rand
  • orderby=meta_value 注:meta_key=keynameは、クエリー内に存在する必要があります。
  • orderby=none – 順序づけしない (バージョン2.8で使用可能)
  • orderby=comment_count – (バージョン2.9で使用可能)
  • orderby=author
  • orderby=date
  • orderby=title
  • orderby=modified
  • orderby=menu_order used most often for Pages (Order field in the Edit Page ・ Attributes box) and attachments (the integer fields in the Insert / Upload Media ・ Gallery dialog), but could be used for any post type with distinct menu_order values (they all default to 0).
  • orderby=parent
  • orderby=ID
  • orderby=rand
  • orderby=meta_value Note: A meta_key=keyname must also be present in the query.
  • orderby=none – no order (available with Version 2.8)
  • orderby=comment_count – (available with Version 2.9)

順序のパラメーター

ORDERBYパラメーターに降順あるいは昇順を指定します。

Designates the ascending or descending order of the ORDERBY parameter.

  • order=ASC – 最大値から最小値に昇順 (1, 2, 3; a, b, c)
  • order=DESC – 最高値から最小値に降順(3, 2, 1; c, b, a)
  • order=ASC – ascending from lowest to highest values (1, 2, 3; a, b, c)
  • order=DESC – descending from highest to lowest values (3, 2, 1; c, b, a)

カスタムフィールドのパラメーター

カスタムフィールドキーあるいは値に基づいて記事(またはページ)を取得します。

Retrieve posts (or Pages) based on a custom field key or value.

  • meta_key=
  • meta_value=
  • meta_compare= – meta_value=をテストするための演算子です。デフォルトは’=’です。他の可能な値では、 ‘!=’, ‘>’, ‘>=’, ‘< ', または '<='
  • meta_key=
  • meta_value=
  • meta_compare= – operator to test the meta_value=, default is ‘=’, with other possible values of ‘!=’, ‘>’, ‘>=’, ‘< ', or '<='

‘color’のキーと’blue’の値の両方にマッチするカスタムフィールドの記事を返します。

Returns posts with custom fields matching both a key of ‘color’ AND a value of ‘blue’:

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

カスタムフィールドの値に関係なく、’color’のカスタムフィールドキーの記事を返します:

Returns posts with a custom field key of ‘color’, regardless of the custom field value:

query_posts('meta_key=color'); 

カスタムフィールドキーに関係なく、カスタムフィールド値が’color’である記事を返します:

Returns posts where the custom field value is ‘color’, regardless of the custom field key:

query_posts('meta_value=color');

カスタムフィールドキーに関係なく、カスタムフィールド値が’green’である任意のページを返します:

Returns any Page where the custom field value is ‘green’, regardless of the custom field key:

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

カスタムフィールド値が’blue’に等しくない、’color’のカスタムフィールドキーで記事とページ両方を返します。

Returns both posts and Pages with a custom field key of ‘color’ where the custom field value IS NOT EQUAL TO ‘blue’:

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

22未満あるいは等しくないカスタムフィールド値で、’miles’のカスタムフィールドキーで記事を返します。99の値は100より大きい、数字ではない文字列として格納されているデータとしてみなされることに注意してください。

Returns posts with custom field key of ‘miles’ with a custom field value that is LESS THAN OR EQUAL TO 22. Note the value 99 will be considered greater than 100 as the data is stored as strings, not numbers.

query_posts('meta_key=miles&amp;meta_compare=<=&amp;meta_value=22');&#91;/php&#93;

<h3>結合のパラメーター</h3>
<p>一部の上記の例から分かるかもしれませんが、アンパサイド(&)でパラメーターを組み合わせます</p>
<blockquote>You may have noticed from some of the examples above that you combine parameters with an ampersand (&), like so:</blockquote>
query_posts('cat=3&amp;year=2004');

メインページに現在の月に対する、カテゴリー13の記事です。

Posts for category 13, for the current month on the main page:

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

2.3での組み合わせは、タイトル降順で、ちょうど2つの記事を表示している、カテゴリー1と3の両方に属している記事を返すだろう。:

At 2.3 this combination will return posts belong to both Category 1 AND 3, showing just two (2) posts, in descending order by the title:

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

2.3と2.5の1では、カテゴリー1に属する”りんご”とタグを付けられた、全ての記事を返すことを受けて期待されるだろう。

In 2.3 and 2.5 one would expect the following to return all posts that belong to category 1 and is tagged “apples”

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

ハプニングからこのバグを防ぎます。チケット#5433を参照してください。回避策はいくつかのタグを使用するための検索です。

A bug prevents this from happening. See Ticket #5433. A workaround is to search for several tags using +

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

これは、前のクエリーに期待された結果を生成します。期待された結果を生成する’cat=1&tag=apples+oranges’を使用するには注意してください。

This will yield the expected results of the previous query. Note that using ‘cat=1&tag=apples+oranges’ yields expected results.

ホームページからカテゴリーを除外する方法

index.phpファイルにこのコードを配置すると、あなたのホームページにカテゴリーID3を除く全てのカテゴリーから記事を表示します。

Placing this code in your index.php file will cause your home page to display posts from all categories except category ID 3.

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

除外リストにいくつかの複数カテゴリーを追加する事も出来ます(WP2.1.2でテスト済み)。

You can also add some more categories to the exclude-list (tested with WP 2.1.2):

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

特定の投稿を取得する方法

特定の記事を取得するために、次のように使う事ができます。

To retrieve a particular post, you could use the following:

<?php
// retrieve one post with an ID of 5
query_posts('p=5');  
?>

このクエリーでもっと読む機能を使いたい場合、global $more変数に0を設定する必要があります。

If you want to use the Read More functionality with this query, you will need to set the global $more variable to 0.

<?php
// retrieve one post with an ID of 5
query_posts('p=5');
  
global $more;
// set $more to 0 in order to only get the first part of the post
$more = 0; 

// the Loop
while (have_posts()) : the_post(); 
  // the content of the post
  the_content('Read the full post ≫'); 
endwhile;
?>

特定のページを取得する方法

特定のページを取得するには、次のように使う事が出来ます:

To retrieve a particular page, you could use the following:

<?php
query_posts('page_id=7');  //retrieves page 7 only
?>

あるいは、

<?php
query_posts('pagename=about'); //retrieves the about page only
?>

子ページでは、スラッシュによって区切られた、親と子のスラッグが必要です。例:

For child pages, the slug of the parent and the child is required, separated by a slash. For example:

<?php
query_posts('pagename=parent/child'); // retrieve the child page of a parent
?>

クエリーポストに変数を渡す方法

あなたのニーズに応じて、2つのメソッドでクエリーの変数を渡す事が出来ます。
他の例と同様に、ループ上にそれらを配置します。:

You can pass a variable to the query with two methods, depending on your needs. As with other examples, place these above your Loop:

例 1

この例では、それを実行する前にクエリーを連結します。まず、変数を割り当てると、その時初めて連結してそれを実行します。ここでは、他の所からカテゴリー変数に引いています。

In this example, we concatenate the query before running it. First assign the variable, then concatenate and then run it. Here we’re pulling in a category variable from elsewhere.

<?php
 $categoryvariable=$cat; // assign the variable as current category
 $query= 'cat=' . $categoryvariable. '&amp;orderby=date&amp;order=ASC'; // concatenate the query
 query_posts($query); // run the query
 ?>

例 2

次の例では、二重引用符はPHPで扱うように表現として囲みます。
この例では、現在の月と現在の月を取得し、現在の月/年として記事を提示するためにquery_postsを扱います。この場合は、ページのトップにある最古の記事を取得するように昇順でリスト化します。

In this next example, the double quotes tell PHP to treat the enclosed as an expression. For this example, we are getting the current month and the current year, and telling query_posts to bring us the posts for the current month/year, and in this case, listing in ascending order so we get the oldest post at the top of the page.

<?php
$current_month = date('m');
$current_year = date('Y');

query_posts("cat=22&amp;year=$current_year&amp;monthnum=$current_month&amp;order=ASC");
?>
&amp;lt;!-- put your loop here --&amp;gt;

例 3

この例では、ページを扱う、記事の一覧を完全に生成するための方法について説明します。
全記事一覧を提示するためのquery_postsに有効な$query_stringをデフォルトで使用する事が出来ます。各ページに表示したい記事数に-1からposts_per_pageクエリーの引数を変更する事も出来ます。;この最後の例では、恐らく生成されたアーカイブを移動するposts_nav_link()を使用するでしょう。

This example explains how to generate a complete list of posts, dealing with pagination. We can use the default $query_string telling query_posts to bring us a full posts listing. We can also modify the posts_per_page query argument from -1 to the number of posts you want to show on each page; in this last case, you’ll probably want to use posts_nav_link() to navigate the generated archive.

<?php 
query_posts($query_string.'&amp;posts_per_page=-1');
while(have_posts()) { the_post();
&amp;lt;!-- put your loop here --&amp;gt;
}
?>

例 4

$query_string変数を使用する必要がない場合、いくつかのより複雑なケースの中に、よりはっきりと読みやすい別のメソッドが存在します。このメソッドは、配列にパラメーターを置きます。例 2の中で同じクエリーとして次のように行う事が出来ます:

If you don’t need to use the $query_string variable, another method exists that is more clear and readable, in some more complex cases. This method puts the parameters into an array. The same query as in Example 2 above could be done like this:

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

あなたが参照する事が出来るように、このアプローチでは、全ての変数は読みやすいように、独自の行に置く事が出来ます。

As you can see, with this approach, every variable can be put on its own line, for easier reading.

オリジナルクエリ(ページ数など)の維持する方法

デフォルトでは、query_postsが実行されることは、完全に現在のページ上の全ての既存のクエリ変数を上書きします。ページ、カテゴリー日付など。失われて、クエリーポストに渡す変数のみが使用されます。

By default running query_posts will completely overwrite all existing query variables on the current page. Pagination, categories dates etc. will be lost and only the variables you pass into query_posts will be used.

元のクエリーに保存したい場合、パラメーターの配列に元のクエリー配列をマージする事が出来ます:

If you want to preserve the original query you can merge the original query array into your parameter array:

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

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

設定>読むに”ブログページは最大限表示する”パラメーターは結果に影響を与える事が出来ます。この問題を解決するには、’posts_per_page’ パラメーターを追加します。例:

The “Blog pages show at most” parameter in Settings > Reading can influence your results. To overcome this, add the ‘posts_per_page’ parameter. For example:

query_posts('category_name=The Category Name&amp;posts_per_page=-1');  //returns ALL from the category

リソース

  • If..Else – Make WordPress Show Only one Post on the Front Page
  • If..Else – Query Posts
  • Perishable Press – 6 Ways to Customize WordPress Post Order
  • nietoperzka’s Custom order of posts on the main page
  • Displaying related category and author content
  • Exclude posts from displaying

関連テンプレートタグ

get_posts, query_posts, rewind_posts, wp_reset_query

Sponsored Link