當(dāng)前位置:首頁>WordPress建站>WordPress開發(fā)>WP_Query 參數(shù):文章、頁面和文章類型

WP_Query 參數(shù):文章、頁面和文章類型

在關(guān)于 WP_Query 系列的這個(gè)部分,你將要學(xué)習(xí)如何使用 WP_Query 來查詢文章、頁面和自定義文章類型。你可以查詢指定的文章和頁面,或者可以運(yùn)行查詢返回一個(gè)或多個(gè)文章類型的文章。

注:由于時(shí)間精力有限,本教程沒辦法翻譯分享,希望朋友們可以加入我們,幫助我們進(jìn)行翻譯,有小酬謝,有意者請聯(lián)系倡萌QQ 745722006(注明:教程翻譯)。

以下為原文:http://code.tutsplus.com/tutorials/wp_query-arguments-posts-pages-and-post-types–cms-23164

In this part of this series on WP_Query, you’ll learn how to use WP_Query to query for posts, pages and custom post types. You can query for specific posts and pages or you can run a query to return posts of one or more post types.

A Recap on How Arguments Work in WP_Query

Before we start, let’s have a quick recap on how arguments work in WP_Query. When you code WP_Query in your themes or plugins, you need to include four main elements:

  • the arguments for the query, using parameters which will be covered in this tutorial
  • the query itself
  • the loop
  • finishing off: closing if and while tags and resetting post data

In practice this will look something like the following:

<?php
 
$args = array(
    // Arguments for your query.
);
 
// Custom query.
$query = new WP_Query( $args );
 
// Check that we have query results.
if ( $query->have_posts() ) {
 
    // Start looping over the query results.
    while ( $query->have_posts() ) {
 
        $query->the_post();
 
        // Contents of the queried post results go here.
 
    }
 
}
 
// Restore original post data.
wp_reset_postdata();
 
?>

The arguments are what tells WordPress what data to fetch from the database and it’s those that I’ll cover here. So all we’re focusing on here is the first part of the code:

$args = array(
    // Arguments for your query.
);

As you can see, the arguments are contained in an array. You’ll learn how to code them as you work through this tutorial.

Coding Your Arguments

There is a specific way to code the arguments in the array, which is as follows:

$args = array(
    'parameter1' => 'value',
    'parameter2' => 'value',
    'parameter3' => 'value'
);

You must enclose the parameters and their values in single quotation marks, use => between them, and separate them with a comma. If you get this wrong, WordPress may not add all of your arguments to the query or you may get a white screen.

Querying for Single Posts or Pages

Let’s start with the simplest scenario: running a query to find one specific post or page.

Querying for One Post

To find a specific post (or set of posts), you have two options:

  • p (int): Use post ID.
  • name (string): Use post slug.

You can use these parameters with any post type including posts, pages, attachments and custom post types. By default WordPress will query for the 'post' post type and not return pages or custom post types—if you want to do this you’ll need to add more arguments or use a different argument, which I’ll come to later in this tutorial.

So, to return a specific post you would use one of these:

$args = array(
    'p' => '32'
);

or:

$args = array(
    'name' => 'post_slug'
);

Note that the name parameter takes the post slug as its argument, not its title.

Using the name parameter makes it easier to identify what your query will fetch from the database when you revisit your code at a later date, but there is the risk that it won’t work if one of your site’s users changes the post slug. The post ID can’t be changed so this is safer.

Querying for One Page

To query for a specific page you have two options again:

  • page_id (int): Use page ID.
  • pagename (string): Use page slug.

So, to run a query fetching just one specific page from the database, you’d use one of these:

$args = array(
    'page_id' => '20'
);

or:

$args = array(
    'pagename' => 'page_slug'
);

Querying for One Post of Another Type

To run a query for a post of another post type, including a custom post type, you’d also use the post_typeparameter. I’ll cover this in a bit more detail later in this tutorial, but in brief, to query for a single post in theproduct custom post type, you’d use this:

$args = array(
    'p' => '46',
    'post_type' => 'product'
);

Or to query for an attachment, you’d use:

$args = array(
    'p' => '46',
    'post_type' => 'attachment'
);

Querying for Child Pages

Sometimes you might need to retrieve all pages that are children of a given page, for example if your site has a hierarchical page structure and you want to display a list on each page of that page’s children.

Note: You wouldn’t do this with posts as they aren’t hierarchical, although you can with a custom post type if it’s hierarchical.

You have three arguments you can use to do this:

  • post_parent (int): Use page ID to return only child pages. Set to 0 to return only top-level entries.
  • post_parent__in (array): Use an array of post IDs.
  • post_parent__not_in (array): Use an array of post IDs.

Let’s take a look at each of them.

The first, post_parent, lets you query for pages which are children of one specific page. 

So to find all pages that are children of a given page, you’d use this:

$args = array(
    'post_type' => 'page',
    'post_parent' => '2'
);

Note that you have to include the post_type argument as the default post type that WP_Query looks for ispost.

Taking this further, this is how you’d use it to find children of the current page:

$current_page_id = get_the_ID();
 
$args = array(
    'post_type' => 'page',
    'post_parent' => $current_page_id
);

You can also use this parameter to identify top level pages, i.e. those without a parent:

$args = array(
    'post_type' => 'page',
    'post_parent' => '0'
);

But what if you want to identify children of multiple pages? You can do this too, with the post_parent__inparameter. This takes an array of post IDs.

So to query for the children of two of your pages, you’d use this:

$args = array(
    'post_type' => 'page',
    'post_parent__in' => array(
        '2',
        '4'
    )
);

You can also exclude child pages from your query, using the post_parent__not_in parameter:

$args = array(
    'post_type' => 'page',
    'post_parent__not_in' => array(
        '2',
        '4'
    )
);

Querying for Multiple Posts

It’s also common to run a query to either include or exclude multiple posts. You have two arguments you can use for this:

  • post__in (array): Use post IDs.
  • post__not_in (array): Use post IDs.

The post__in argument can be used for all post types and takes an array of IDs. So to output a list of specific posts, you’d use this:

$args = array(
    'post__in' => array(
        '36',
        '52',
        '246',
        '354'
    )
);

Note: If you use this argument to fetch posts, WordPress will still fetch sticky posts, even if they’re not in your list. To omit them, you use the ignore_sticky_posts argument:

$args = array(
    'post__in' => array(
        '36',
        '52',
        '246',
        '354'
    ),
    'ignore_sticky_posts' => 'true'
);

The post__not_in argument works in a similar way, again taking an array of post IDs, but it will output everything else except the posts listed. You’d normally combine it with other arguments to avoid outputting a huge list of posts.

So to query for all posts of the product post type but exclude a few:

$args = array(
    'post_type' => 'product',
    'post__not_in' => array(
        '36',
        '52',
        '246',
        '354'
    )
);

So to combine this with one of our earlier examples, here’s how you’d query for all top level pages except the current one:

$current_page_ids = array( get_the_ID() );
 
$args = array(
    'post_parent' => '0',
    'post__not_in' => $current_page_ids
);

Note that if you’ve also registered a hierarchical post type, you’ll need to include the post_type parameter in this code to just query for pages.

Querying for Post Types

In some of the examples above I’ve used the post_type parameter to identify posts of a certain type. Let’s take a look at the arguments you can use with that parameter:

  • post: A post.
  • page: A page.
  • revision: A revision.
  • attachment: An attachment.
  • nav_menu_item: A navigation menu item.
  • any: Retrieves any type except revisions and types with 'exclude_from_search' set to true when they were registered.
  • Custom Post Types (e.g. product).

As we’ve seen above you can use this parameter with other arguments to make your query more specific.

So to give a simple example, here’s how you’d query for all of your site’s pages:

$args = array(
    'post_type' => 'page'
);

Custom Post Types

Querying for a custom post type is simple: use the name you gave the post type when registering it, not the title that’s used in the admin menus. So let’s say you registered your product post types usingregister_post_type() as follows:

function register_product() {
 
    $args = array(
        'name' => __( 'Products', 'tutsplus' ),
        'singular_name' => __( 'Product', 'tutsplus' )
    );
 
    register_post_type( 'product', $args );
}

The value you use for the post_type argument when querying for products isn’t 'Product' or 'Products' but'product':

$args = array(
    'post_type' => 'product'
);

Attachments

By default if you try to run a query for attachments it won’t work, as WordPress sets the post_status of attachments to inherit and WP_Query defaults to 'post_status' => 'publish' unless you specify otherwise. So if you want to query for attachments you must include the post_status argument:

$args = array(
    'post_type' => 'attachment',
    'post_status' => 'inherit'
);

Note that you could also use any instead of inherit.

Summary

Using WP_Query to create custom queries for posts and post types is something I do a lot. As you’ve seen from the examples here, there are plenty of possibilities:

  • Use it to query for top level pages in your site.
  • Use it to query for posts of a specific post type.
  • Use it to query for all posts except the ones you specify.
  • Use it to query for all the children of the current page.

There are many more possibilities using the arguments covered here, but this should give you a taster.

聲明:本站所有文章,如無特殊說明或標(biāo)注,均為本站原創(chuàng)發(fā)布。任何個(gè)人或組織,在未征得本站同意時(shí),禁止復(fù)制、盜用、采集、發(fā)布本站內(nèi)容到任何網(wǎng)站、書籍等各類媒體平臺。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。

給TA打賞
共{{data.count}}人
人已打賞
歡迎關(guān)注WordPress大學(xué)公眾號 WPDAXUE
WordPress開發(fā)

理解和利用 WordPress 中的內(nèi)容類型

2016-4-15 10:10:52

WordPress開發(fā)

WP_Query 參數(shù):分類和標(biāo)簽

2016-4-21 8:00:38

0 條回復(fù) A文章作者 M管理員
    暫無討論,說說你的看法吧
?
個(gè)人中心
購物車
優(yōu)惠劵
今日簽到
有新私信 私信列表
搜索

江陵县| 牡丹江市| 宣恩县| 伊宁县| 吴江市| 秦皇岛市| 英德市| 永川市| 墨脱县| 屏东县| 双牌县| 栾川县| 赤水市| 二手房| 天峻县| 乐亭县| 都匀市| 阿拉善盟| 平遥县| 宜丰县| 京山县| 那曲县| 全州县| 应城市| 永宁县| 安徽省| 项城市| 岑溪市| 揭东县| 荔浦县| 安仁县| 藁城市| 吴忠市| 前郭尔| 蛟河市| 普定县| 正蓝旗| 通化县| 永胜县| 凤凰县| 贵阳市|