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
-
-
if (is_home()) {
-
Query_posts("cat=-3");
-
}
-
?>
You can also exclude more categories.
Php code
-
-
if (is_home()) {
-
Query_posts("cat=-1,-2,-3");
-
}
-
?>
2. Query the specified article
Use the following statement to retrieve a specified article:
Php code
-
-
//Get the article with ID value 5
-
query_posts('p=5');
-
?>
If you want to use the Read More function in the query statement, please set the global variable $more to 0.
Php code
-
-
//Get the page with ID value 5
-
query_posts('p=5');
-
-
global $more;
-
//Initialize $more
-
$more = 0;
-
-
//Loop query results
-
while (have_posts()) : the_post();
-
the_content('Read the full post ?');
-
endwhile;
-
?>
3. Retrieve the specified page
Use the following statement to retrieve a specified page:
Php code
-
-
query_posts('page_id=7'); //Get the page with page ID 7
-
?>
or
Php code
-
-
query_posts('pagename=about');
-
?>
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
-
-
query_posts('pagename=parent/child');
-
?>
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
-
query_posts(array(
-
'cat' => 22,
-
'year' => $current_year,
-
'monthnum' => $current_month,
-
'order' => 'ASC',
-
));
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
-
query_posts('cat=4');
Display a single category based on category name
Only display articles from a certain category name:
Php code
-
query_posts('category_name=Staff Home');
Show multiple categories based on ID
Display articles from several specified category IDs:
Php code
-
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
-
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
-
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
-
query_posts(array('category__in' => array(2,6)));
You can exclude articles in multiple categories in the following way:
Php code
-
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
-
query_posts('tag=cooking');
Get articles in any of several tags
Php code
-
query_posts('tag=bread+baking+recipe');
Multiple tags
Display articles belonging to tags with IDs 37 and 47:
Php code
-
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
-
query_posts(array('tag__in' => array(37,47));
The displayed article belongs to neither tag 37 nor tag 47:
Php code
-
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
-
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
-
$sticky=get_option('sticky_posts') ;
-
query_posts('p=' . $sticky[0]);
or
Php code
-
$args = array(
-
'posts_per_page' => 1,
-
'post__in' => get_option('sticky_posts'),
-
'caller_get_posts' => 1
-
);
-
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
-
$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...
-
}
Exclude all pinned articles from the query
Php code
-
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
-
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
-
-
$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);
-
?>
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
-
$today = getdate();
-
query_posts('year=' .$today["year"] .'&monthnum=' .$today["mon"] .'&day=' .$today["mday"] );
Return to the article published on December 20th
Php code
-
query_posts(monthnum=12&day=20' );
Return to articles published between March 1st and March 15th, 2009
Php code
-
-
//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
-
Return $where;
-
}
-
add_filter('posts_where', 'filter_where');
-
query_posts($query_string);
-
?>
Return to articles published in the last 30 days
Php code
-
-
//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);
-
?>
Return to articles published in the past 30 days to the past 60 days
Php code
-
-
//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
-
Return $where;
-
}
-
add_filter('posts_where', 'filter_where');
-
query_posts($query_string);
-
?>
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
-
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
-
query_posts('meta_key=color&metavalue=blue');
Return articles with the custom field keyword 'color', regardless of the custom field value:
Php code
-
query_posts('meta_key=color');
Return articles with custom field value 'color', regardless of keyword:
Php code
-
query_posts('metavalue=color');
Return pages where the custom field value is 'green', regardless of the custom field keyword:
Php code
-
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
-
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('meta_key=miles&meta_compare=<=&metavalue=22');
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
-
uery_posts('cat=3&year=2004');
Display articles on the homepage published in the current month and belonging to category 13:
Php code
-
if (is_home()) {
-
query_posts($query_string . '&cat=13&monthnum=' . date('n',current_time('timestamp')));
-
}
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
-
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
-
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
-
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
-
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
http://www.bkjia.com/PHPjc/735067.htmlwww.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...