Home > Backend Development > PHP Tutorial > Powerful query_posts() function in wordpress_PHP tutorial

Powerful query_posts() function in wordpress_PHP tutorial

WBOY
Release: 2016-07-13 10:38:41
Original
1923 people have browsed it

Today I will talk about the main query function of WordPress -query_posts(), because I have used this function many times in the theme I am making.

The query_posts() query function determines which posts appear in the WordPress main loop. Because of this, the query_posts function is only used to modify the home page loop (Loop), rather than generating secondary loops on the page. If you want to generate additional loops outside the main loop, you should create new independent WP_Query objects and use these objects to generate loops. Using query_posts on a loop outside of the main loop will cause the main loop to run skewed and may display content on the page that you don't want to see.

The query_posts() query function receives a large number of parameters, and the format is the same as the parameter format in the URL (for example, p=4 means the article with ID 4). Here are some examples of some commonly used syntax formats of the query_posts function.

1. Exclude certain categories from the blog homepage

Add the following code to the index.php file so that the articles displayed on the homepage can come from any category except category 3.

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. if (is_home()) {
  2. Query_posts("cat=-3");
  3. ?>

You can also exclude more categories.

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. if (is_home()) {
  2. Query_posts("cat=-1,-2,-3");
  3. ?>
2. Query the specified article

Use the following statement to retrieve a specified article:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. //Get the article with ID value 5
  2. query_posts('p=5');
  3. ?>

If you want to use the Read More function in the query statement, please set the global variable $more to 0.

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. //Get the page with ID value 5
  2. query_posts('p=5');
  3. global $more;
  4. //Initialize $more
  5. $more = 0;
  6. //Loop query results
  7. while (have_posts()) : the_post();
  8. the_content('Read the full post ?');
  9. endwhile;
  10. ?>
3. Retrieve the specified page

Use the following statement to retrieve a specified page:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('page_id=7'); //Get the page with page ID 7
  2. ?>

or

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('pagename=about');
  2. ?>

When retrieving a subpage, you need to provide the alias of the subpage and its parent page, separating the two with a slash. For example:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('pagename=parent/child');
  2. ?>

The above methods all use the form of query_posts($query_string) to call this function. Here is another method to pass parameter variables using an array.

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array(
  2. 'cat' => 22,
  3. 'year' => $current_year,
  4. 'monthnum' => $current_month,
  5. 'order' => 'ASC',
  6. ));

Compared with the string method, the array form is more intuitive and less error-prone.

Below are some frequently used parameters. Some of them have been used by me, and some have not been used. Let’s just summarize them.

Classification parameters

Only show articles under specific categories.

  • cat - must use category ID
  • category_name
  • category_and —— must use category ID
  • category_in - must use category ID
  • category_not_in - must use category ID

Display a single category based on ID

Only display articles from a certain category ID (and subcategories under this category):

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('cat=4');

Display a single category based on category name

Only display articles from a certain category name:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('category_name=Staff Home');

Show multiple categories based on ID

Display articles from several specified category IDs:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('cat=2,6,17,38');

Exclude articles in a certain category

Displays all articles except articles in a certain category. Excluded category IDs are prefixed with a minus sign ('-').

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('cat=-3');

The above code deletes articles in the category with ID 3.

Handle multiple categories

Display articles belonging to multiple categories. The following code can display articles belonging to both category 2 and category 6:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array('category__and' => array(2,6)));

If you want to display articles in category 2 or category 6, you can use the cat introduced above, or you can use the category_in function (note that articles in subcategories under the category will not be displayed here):

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array('category__in' => array(2,6)));

You can exclude articles in multiple categories in the following way:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array('category__not_in' => array(2,6)));

Tag parameters

Display articles under a specific tag.

  • 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 articles in a certain tag

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('tag=cooking');

Get articles in any of several tags

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('tag=bread+baking+recipe');

Multiple tags

Display articles belonging to tags with IDs 37 and 47:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array('tag__and' => array(37,47));

To display articles under tags with ID 37 or 47, you can use the tag parameter or tag_in:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array('tag__in' => array(37,47));

The displayed article belongs to neither tag 37 nor tag 47:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array('tag__not_in' => array(37,47));

tag_slug_in works almost the same as tag_slug_and, except that the matching aliases are different.

Author parameters

You can also select articles based on their authors.

  • author=3
  • author=-3 ——Exclude articles published by authors with ID 3
  • author_name=Harriet

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

Display all pages published by the author with ID 1, arrange the pages in title order, and there is no pinned article above the page list:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('caller_get_posts=1&author=1&post_type=page&post_status=publish&orderby=title&order=ASC');

Article & page parameters

Retrieve a single article or page.

  • ‘p’ => 27 - Display the article by article ID
  • ‘name’ => ‘about-my-life’ —— query for a certain article, the query contains the article alias
  • ‘page_id’ => 7 —— Query for the page with ID 7
  • ‘pagename’ => ‘about’ —— Note that this is not the page title, but the page path
  • Use ‘posts_per_page’ => 1 – use ‘posts_per_page’ => 3 to display 3 articles. Use 'posts_per_page' => -1 to display all posts
  • ‘showposts’ => 1 – use ‘showposts’ => 3 to display 3 posts. Use 'showposts' => -1 to display all posts. Deprecated.
  • ‘post__in’ => array(5,12,2,14,7) ——Specify the article ID you want to retrieve
  • ‘post__not_in’ => array(6,2,8) ——Exclude article IDs that you do not want to retrieve
  • ‘post_type’ => ‘page’ ——Return page; default value is post; available values ​​include any, attachment, page, post or revision. any retrieves all page types except revisions.
  • ‘post_status’ => ‘publish’ – Returns the published page. Available values ​​also include pending, draft, future, private, trash. For information about inherit, see get_children. The trash status was added in WordPress 2.9.
  • ‘post_parent’ => 93 - Returns the subpages of page 93.

Pinned article parameters

The pinned article feature was introduced in WordPress 2.7. In the query, the article set as "top" will be displayed before other articles, unless the article has been excluded by the caller_get_posts=1 parameter.

  • array(‘post__in’=>get_option(‘sticky_posts’)) —— Returns an array of all sticky posts
  • caller_get_posts=1 - Exclude pinned articles above the returned articles, but when returning the post list, place the pinned articles in the list in natural order.

Return to the first pinned article

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. $sticky=get_option('sticky_posts') ;
  2. query_posts('p=' . $sticky[0]);

or

Php code Powerful query_posts() function in wordpress_PHP tutorial
  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 latest pinned article; if there is no pinned article currently, return the latest published article.

Return to the first pinned article; if there is none, no content will be returned

Php code Powerful query_posts() function in wordpress_PHP tutorial
  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 Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array("post__not_in" =>get_option("sticky_posts")));

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

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('caller_get_posts=1&posts_per_page=3&cat=6');

Return to all articles under a certain category, do not display pinned articles at all, and retain paging

Php code Powerful query_posts() function in wordpress_PHP tutorial
  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 parameter

Search for articles published within a specific time period.

  • hour= -hour (hour, - ranges from 0 to 23)
  • minute= – minute (minute, - range from 0 to 60)
  • second= – second (seconds, - ranges from 0 to 60)
  • day= – day of the month (day, - ranging from 1 to 31)
  • monthnum= – month number (month, - range from 1 to 12)
  • year= – 4 digit year (year, such as 2009)
  • w= – week of the year (week of the year, - ranging from 0 to 53), use the MySQL WEEK command Mode=1 command

Return to recently published articles

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. $today = getdate();
  2. query_posts('year=' .$today["year"] .'&monthnum=' .$today["mon"] .'&day=' .$today["mday"] );

Return to the article published on December 20th

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(monthnum=12&day=20' );

Return to articles published between March 1st and March 15th, 2009

Php code Powerful query_posts() function in wordpress_PHP tutorial
  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
  5. Return $where;
  6. add_filter('posts_where', 'filter_where');
  7. query_posts($query_string);
  8. ?>

Return to articles published in the last 30 days

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. //based on Austin Matzko's code from wp-hackers email list
  2. function filter_where($where = '') {
  3. //posts in the last 30 days
  4. $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
  5. Return $where;
  6. add_filter('posts_where', 'filter_where');
  7. query_posts($query_string);
  8. ?>

Return to articles published in the past 30 days to the past 60 days

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. //based on Austin Matzko's code from wp-hackers email list
  2. function filter_where($where = '') {
  3. //posts 30 to 60 days old
  4. $where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date
  5. Return $where;
  6. add_filter('posts_where', 'filter_where');
  7. query_posts($query_string);
  8. ?>

Pagination parameters

  • paged=2 - Displays articles that appear on the second page after clicking the "Older Posts" link
  • posts_per_page=10 - The number of posts displayed on each page; if the value is -1, all posts will be displayed.
  • order=ASC - displays articles in chronological order, if the value is DESC, displays articles in reverse chronological order (default)

offset parameter

Through the offset parameter, you can remove or ignore one or more initial articles in the query set under normal circumstances.

The following shows the 5 posts following the most recent post:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('posts_per_page=5&offset=1');

Sorting parameters

  • orderby=author
  • orderby=date
  • orderby=category - Note: This parameter cannot be used in WordPress 2.8 and may have been deprecated
  • orderby=title
  • orderby=modified
  • orderby=menu_order
  • orderby=parent
  • orderby=ID
  • orderby=rand
  • orderby=meta_value - meta_key=some value statement should also appear in query parameters
  • orderby=none – no order —— (new in WP 2.8)
  • orderby=comment_count ——(new in WP 2.9)

Order parameters

Decide whether to sort in ascending or descending orderSort parameter

  • order=ASC - ascending order, from lowest value to highest value
  • order=DESC - Descending order, from highest value to lowest value

Custom field parameters

Retrieve articles (or pages) based on custom keywords or values.

  • meta_key=
  • metavalue=
  • meta_compare= - operator used to test metavalue=, the default value is '=', other possible values ​​include '!=', '>', '>=', '

Return articles with the keyword 'color' and the value 'blue':

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('meta_key=color&metavalue=blue');

Return articles with the custom field keyword 'color', regardless of the custom field value:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('meta_key=color');

Return articles with custom field value 'color', regardless of keyword:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('metavalue=color');

Return pages where the custom field value is 'green', regardless of the custom field keyword:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('post_type=page&metavalue=green');

Return articles and pages whose custom keyword is 'color' and whose custom field value is not 'blue':

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('post_type=any&meta_key=color&meta_compare=!=&metavalue=blue');

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

query_posts(&#39;meta_key=miles&meta_compare=<=&metavalue=22&#39;);
Copy after login

Joint parameters

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

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. uery_posts('cat=3&year=2004');

Display articles on the homepage published in the current month and belonging to category 13:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  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 union returns two articles that belong to both category 1 and category 3, in descending order by article title:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts(array('category__and'=>array(1,3),'posts_per_page'=>2,'orderby'=>title,'order'=>DESC));

In WP 2.3 and WP 2.5, the following parameter combination should return articles belonging to category 1 with the "apples" tag:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('cat=1&tag=apples');

But due to a bug, the code failed to show normal results. There is a solution: use the + sign to find multiple tags:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('cat=1&tag=apples+apples');

This shows the results we want to show.

Usage Tips

The "Maximum blog pages to display" parameter in Settings > Reading will affect your query results. To override the setting in Settings > Reading, you need to add the 'posts_per_page' parameter to the tag. For example:

Php code Powerful query_posts() function in wordpress_PHP tutorial
  1. query_posts('category_name=The Category Name&posts_per_page=-1'); //returns ALL from the category

Note: The query_posts function will rewrite and replace the main query of the page. As a precaution, please do not use query_posts for other purposes.

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735067.htmlTechArticleToday I will talk about the main query function of WordPress - query_posts(), because it is used many times in the theme I am making. this function. The query_posts() query function determines which articles appear in Wo...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template