The powerful query_posts () function _php Tutorial in WordPress

Source: Internet
Author: User
Today talk about WordPress's main query function-query_posts (), because I am working on the theme of the use of this function many times.

The query_posts () query function determines which articles appear in the main WordPress loop (loop), and because of this, the Query_posts function is only used to modify the home loop (loop) instead of generating secondary loops on the page. If you want to generate loops outside of the main loop, you should create a new, separate Wp_query object that generates loops with these objects. Using Query_posts on a loop outside of the main loop causes the main loop to run out of bias and may display content that you do not want to see on the page.

The query_posts () query function function receives a large number of parameters in the same format as the parameter in the URL (for example, p=4 represents an article with ID 4). Here are some examples of common syntax formats for query_posts functions.

1. Exclude certain categories from the blog home page

Add the following code to the index.php file so that the article displayed on the home page can come from any classification other than Category 3.

PHP code
    1. if (Is_home ()) {
    2. Query_posts ("cat=-3");
    3. }
    4. ?>

You can also rule out a few more categories.

PHP code
    1. if (Is_home ()) {
    2. Query_posts ("cat=-1,-2,-3");
    3. }
    4. ?>

2. Query the specified article

Retrieve a specified article with the following statement:

PHP code
    1. Get an article with an ID value of 5
    2. Query_posts (' p=5 ');
    3. ?>

If you want to use the Read more feature in a query statement, set the global variable $more to 0.

PHP code
    1. Get a page with an ID value of 5
    2. Query_posts (' p=5 ');
    3. Global $more;
    4. Initialize $more
    5. $more = 0;
    6. The results of a circular query
    7. while (Have_posts ()): The_post ();
    8. The_content (' Read the full post? ');
    9. Endwhile;
    10. ?>

3. Retrieving the specified page

Retrieve a specified page using the following statement:

PHP code
    1. Query_posts (' page_id=7 '); Get page with page ID 7
    2. ?>

Or

PHP code
    1. Query_posts (' pagename=about ');
    2. ?>

When retrieving a child page, you need to provide an alias for the child page and its parent page, separated by a slash. For example:

PHP code
    1. Query_posts (' Pagename=parent/child ');
    2. ?>

All of this is done using query_posts ($query _string) to invoke the function, and here's another way to pass a parameter variable with an array.

PHP code
    1. Query_posts (Array (
    2. ' Cat ' = 22,
    3. ' Year ' = $current _year,
    4. ' Monthnum ' = $current _month,
    5. ' Order ' = ' ASC ',
    6. ));

The array form is more intuitive and less error-prone than the string method.

The following to organize some of the commonly used parameters, some of which I have used, and some do not, counted as induction bar.

Classification parameters

Displays only articles under a specific category.

    • cat--must use the category ID
    • Category_name
    • category_and--must use the category ID
    • category_in--must use the category ID
    • category_not_in--must use the category ID

Display a single category by ID

Show only articles from a single catalog ID (and sub-categories in the category directory):

PHP code
    1. Query_posts (' cat=4 ');

Display a single category by category name

Show only articles from a category name:

PHP code
    1. Query_posts (' Category_name=staff Home ');

Display multiple categories by ID

Displays the articles from several specified catalog IDs:

PHP code
    1. Query_posts (' cat=2,6,17,38 ');

Exclude articles in a category

Displays all articles except a category article, the excluded category ID is prefixed with a minus sign ('-').

PHP code
    1. Query_posts (' cat=-3 ');

The above code removes the article in the category with ID 3.

Working with multiple classifications

Displays articles that belong to multiple classifications. The following code shows an article that belongs to both Category 2 and Category 6:

PHP code
    1. Query_posts (Array (' category__and ' = = Array (2,6)));

If you want to display the articles in category 2 or Category 6, you can use the cat described above, or you can use the CATEGORY_IN function (note that the articles in the subcategories below are not shown here):

PHP code
    1. Query_posts (Array (' category__in ' = = Array (2,6)));

You can exclude articles from multiple categories in this way:

PHP code
    1. Query_posts (Array (' category__not_in ' = = Array (2,6)));

Label parameters

Displays the article under a specific label.

    • tag--must use Tag ID
    • tag_id--must use Tag ID
    • tag_and--must use Tag ID
    • tag_in--must use Tag ID
    • tag_not_in--must use Tag ID
    • tag_slug_and--must use Tag ID
    • tag_slug_in--must use Tag ID

Get an article in a label

PHP code
    1. Query_posts (' tag=cooking ');

Get articles from any tab in a number of tags

PHP code
    1. Query_posts (' tag=bread+baking+recipe ');

Multiple labels

Displays the article under the label with both IDs 37 and 47:

PHP code
    1. Query_posts (Array (' tag__and ' = = Array (37,47));

To display an article under a label with an ID of 37 or 47, you can use the tag parameter or tag_in:

PHP code
    1. Query_posts (Array (' tag__in ' = = Array (37,47));

The displayed article does not belong to label 37 or label 47:

PHP code
    1. Query_posts (Array (' tag__not_in ' = = Array (37,47));

Tag_slug_in works almost the same way as Tag_slug_and, except that the matching aliases are different.

Author parameters

You can also choose the article according to the author.

    • Author=3
    • author=-3--exclude an article published by an author with ID 3
    • Author_name=harriet

Note: Author_name runs on the User_nicename field, and author runs on the Author ID field.

Displays all pages published by the author with ID 1, in the order of headings, with no pinned articles above the page list:

PHP code
    1. Query_posts (' caller_get_posts=1&author=1&post_type=page&post_status=publish&orderby=title& Order=asc ');

Articles & Page Parameters

Retrieves a single article or page.

    • ' P ' = + 27--Show this article by article ID
    • ' Name ' = ' about-my-life '--a query for an article that contains an article alias
    • ' page_id ' + 7--query for pages with ID 7
    • ' PageName ' = ' about '--note that this is not the page title, but the page path
    • With ' posts_per_page ' and 1–use ' Posts_per_page ' + 3 show 3 articles. Show all articles with ' posts_per_page ' +-1
    • ' Showposts ' and 1–use ' showposts ' + 3 show 3 articles. Show all articles with ' showposts ' +-1. is deprecated.
    • ' post__in ' = = Array (5,12,2,14,7)--Specifies the ID of the article you want to retrieve
    • ' post__not_in ' = = Array (6,2,8)--excludes article IDs that you do not want to retrieve
    • ' Post_type ' + ' page '-returns the page; The default value is post; Available values include any, attachment, page, post, or revision. Any to retrieve all page types except revisions.
    • ' Post_status ' = ' publish '--returns to the published page. Available values also include pending, draft, future, private, trash. For inherit please see Get_children. Trash status added to WordPress 2.9.
    • ' Post_parent ' = 93--Returns a sub-page of page 93.

Sticky article parameters

Featured article features introduced in WordPress 2.7. In queries, articles that are set as "pinned" appear before other articles unless the article has been excluded by the caller_get_posts=1 parameter.

    • Array (' post__in ' =>get_option (' sticky_posts '))--Returns the arrays of all the pinned articles
    • caller_get_posts=1--excludes pinned articles from the top of the returned articles, but when you return to the list of articles, the previously pinned articles are placed in the list in a natural order.

Return to the first sticky article

PHP code
    1. $sticky =get_option (' sticky_posts ');
    2. Query_posts (' p= '. $sticky [0]);

Or

PHP code
    1. $args = Array (
    2. ' Posts_per_page ' = 1,
    3. ' Post__in ' = get_option (' sticky_posts '),
    4. ' Caller_get_posts ' = 1
    5. );
    6. Query_posts ($args);

Note: The second method can only return the most recently published pinned article, and if there is no current pinned article, return to the latest published article.

Returns the first pinned article, if none, returns no content

PHP code
    1. $sticky = get_option (' sticky_posts ');
    2. $args = Array (
    3. ' Posts_per_page ' = 1,
    4. ' Post__in ' = $sticky,
    5. ' Caller_get_posts ' = 1
    6. );
    7. Query_posts ($args);
    8. if ($sticky [0]) {
    9. Insert here your stuff ...
    10. }

Exclude all pinned articles from the query

PHP code
    1. Query_posts (Array ("Post__not_in" =>get_option ("sticky_posts"));

Returns all articles under a category, but does not display a pinned article above the list of articles. All posts that are set to "pinned" appear in normal order (such as date order)

PHP code
    1. Query_posts (' caller_get_posts=1&posts_per_page=3&cat=6 ');

Returns all articles under a category, without displaying sticky articles at all, preserving pagination

PHP code
    1. $paged = (Get_query_var (' paged '))? Get_query_var (' paged '): 1;
    2. $sticky =get_option (' sticky_posts ');
    3. $args =array (
    4. ' Cat ' =>3,
    5. ' Caller_get_posts ' =>1,
    6. ' Post__not_in ' = $sticky,
    7. ' Paged ' = $paged,
    8. );
    9. Query_posts ($args);
    10. ?>

Time parameters

Retrieve articles published during a specific time period.

    • Hour=-hour (time,-range from 0 to 23)
    • Minute=–minute (min,-range from 0 to 60)
    • Second=–second (sec,-range from 0 to 60)
    • Day=–day of the month (day,-range from 1 to 31)
    • Monthnum=–month number (month,-range from 1 to 12)
    • Year=–4 Digit year (for example, 2009)
    • W=–week of the year (the week of the first, the range from 0 to 53), using the MySQL Week command mode=1 commands

Back to recently published articles

PHP code
    1. $today = getdate ();
    2. Query_posts (' year= '. $today ["Year"]. ' &monthnum= '. $today ["Mon"]. ' &day= '. $today ["Mday"]);

Back to articles published on December 20

PHP code
    1. Query_posts (monthnum=12&day=20 ');

Return to the article published between March 1, 2009 and March 15

PHP code
    1. Based on Austin Matzko ' s code from wp-hackers email list
    2. function Filter_where ($where = ") {
    3. Posts for March 1 to March 15, 2009
    4. $where. = "and post_date >= ' 2009-03-01 ' and Post_date < ' 2009-03-16 '";
    5. return $where;
    6. }
    7. Add_filter (' Posts_where ', ' filter_where ');
    8. Query_posts ($query _string);
    9. ?>

Return articles published within the last 30 days

PHP code
    1. Based on Austin Matzko ' s code from wp-hackers email list
    2. function Filter_where ($where = ") {
    3. Posts in the last
    4. $where. = "and Post_date >". Date (' y-m-d ', Strtotime (' -30 days ')). "'";
    5. return $where;
    6. }
    7. Add_filter (' Posts_where ', ' filter_where ');
    8. Query_posts ($query _string);
    9. ?>

Returns articles published in the past 30 days to the last 60 days

PHP code
    1. Based on Austin Matzko ' s code from wp-hackers email list
    2. function Filter_where ($where = ") {
    3. Posts to
    4. $where. = "and Post_date >= '". Date (' y-m-d ', Strtotime (' -60 days ')). "'" . " and Post_date <= ' ". Date (' y-m-d ', Strtotime (' -30 days ')). "'";
    5. return $where;
    6. }
    7. Add_filter (' Posts_where ', ' filter_where ');
    8. Query_posts ($query _string);
    9. ?>

Paging parameters

    • paged=2--show the article that appears on the second page after clicking on the "Older log" link
    • posts_per_page=10--the number of articles displayed per page; If 1, all articles are displayed.
    • order=asc--the article in chronological order, and if the value is DESC, displays the article in reverse chronological order (default)

Offset (SHIFT) parameter

With the offset parameter, you can remove or omit one or more of the initial articles in the query set that are normally being queried.

The following 5 articles are displayed after the most recent article:

PHP code
    1. Query_posts (' posts_per_page=5&offset=1 ');

Sorting parameters

    • Orderby=author
    • Orderby=date
    • orderby=category--NOTE: This parameter cannot be used with WordPress 2.8 and may have been revoked
    • Orderby=title
    • Orderby=modified
    • Orderby=menu_order
    • Orderby=parent
    • Orderby=id
    • Orderby=rand
    • The Orderby=meta_value--meta_key=some value statement should also appear in the query parameters
    • Orderby=none–no order--(added to WP 2.8)
    • orderby=comment_count--(added to WP 2.9)

Sequential parameters

Decide to arrange the sort parameters in ascending or descending order

    • order=asc--ascending, from lowest value to highest value
    • order=desc--Descending, from highest value to lowest value

custom field Parameters

Retrieves an article (or page) based on a custom keyword or value.

    • meta_key=
    • Metavalue=
    • meta_compare=--is used to test the metavalue= operator, the default value is ' = ', and other possible values include '! = ', ' > ', ' >= ', ' < ' or ' <= '.

Return an article with the keyword ' color ' and a value of ' blue ':

PHP code
    1. Query_posts (' Meta_key=color&metavalue=blue ');

Returns an article with a custom field keyword of ' color ', regardless of the custom field value:

PHP code
    1. Query_posts (' Meta_key=color ');

Returns an article with a custom field value of ' color ', regardless of the keyword:

PHP code
    1. Query_posts (' Metavalue=color ');

Returns a page with a custom field value of ' green ', regardless of the custom field keyword:

PHP code
    1. Query_posts (' Post_type=page&metavalue=green ');

Returns articles and pages for which the custom keyword is ' color ' and the custom field value is not ' blue ':

PHP code
    1. Query_posts (' Post_type=any&meta_key=color&meta_compare=!=&metavalue=blue ');

Returns an article with a custom field keyword of ' Miles ' and a custom field value of less than or equal to 22. Note that the field value of 99 is considered to be greater than the field value 100 because the data is stored as a string rather than as a number.

Query_posts (' meta_key=miles&meta_compare=<=&metavalue=22 ');

Union parameters

You may have seen some of the above examples, you can use the & symbol to connect different parameters, such as:

PHP code
    1. Uery_posts (' cat=3&year=2004 ');

Displays the article on the Home page, published in the current month, under category 13:

PHP code
    1. if (Is_home ()) {
    2. Query_posts ($query _string. ' &cat=13&monthnum= '. Date (' n ', current_time (' timestamp ')));
    3. }

In WP 2.3, the following parameter federation returns two articles belonging to both Category 1 and Category 3, sorted in descending order of article headings:

PHP code
    1. Query_posts (Array (' Category__and ' =>array (1,3), ' posts_per_page ' =>2, ' order by ' =>title, ' an ', ' =>desc ')) ;

In WP 2.3 and WP 2.5, the following combination of parameters should return the article belongs to Category 1 with the "Apples" label:

PHP code
    1. Query_posts (' cat=1&tag=apples ');

However, because of a bug, the code does not show the normal results. There is a workaround: Use the + sign to find multiple tags:

PHP code
    1. Query_posts (' cat=1&tag=apples+apples ');

This shows the results we want to show.

Tips for use

Settings > read the "blog page max" parameter will affect your query results, to override settings > Reading settings, you need to add the ' posts_per_page ' parameter to the tag. For example:

PHP code
    1. Query_posts (' category_name=the category Name&posts_per_page=-1 '); Returns all from the category

Note: The Query_posts function overwrites and replaces the main query of the page. For the sake of caution, please do not use query_posts for other purposes.

Source: http://www.zuluo.net/2012/2012-01/wordpress-query_posts.html

http://www.bkjia.com/PHPjc/735067.html www.bkjia.com true http://www.bkjia.com/PHPjc/735067.html techarticle today talk about WordPress's main query function-query_posts (), because I am working on the theme of the use of this function many times. The query_posts () query function determines which articles appear in wo ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.