Home >Backend Development >PHP Tutorial >WP_Query Arguments: Posts, Pages, and Post Types
In this part of this series on page_id in our example. This 20 is cast to an integer because post_status argument to post__in argument to fetch posts, WordPress will still fetch sticky posts, even if they're not in your list, as you can see in the image above. To omit them, you use the post__in and post_type parameter in this code to just query for pages.
In some of the examples above, I've used the post_type is usually set to any whenever you use the tax_query<code>tax_query
argument in your queries.
To give a simple example, here's how you'd query for all of your site's pages:
$args = array(<br> 'post_type' => 'page'<br>);<br>
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 using register_post_type()<code>register_post_type()
as follows:
function register_product() {<br><br> $args = array(<br> 'name' => __( 'Products', 'tutsplus' ),<br> 'singular_name' => __( 'Product', 'tutsplus' )<br> );<br><br> register_post_type( 'product', $args );<br>}<br>
The value you use for the post_type<code>post_type
argument when querying for products isn't 'Product'<code>'Product'
or 'Products'<code>'Products'
but 'product'<code>'product'
:
$args = array(<br> 'post_type' => 'product'<br>);<br>
By default, if you try to run a query for attachments, it won't work. That's because WordPress sets the post_status<code>post_status
of attachments to inherit<code>inherit
and WP_Query<code>WP_Query
defaults to 'post_status' => 'publish'<code>'post_status' => 'publish'
unless you specify otherwise. So if you want to query for attachments, you must include the post_status<code>post_status
argument:
$args = array(<br> 'post_type' => 'attachment',<br> 'post_status' => 'inherit'<br>);<br>
Note that you could also use any<code>any
instead of inherit<code>inherit
.
Using WP_Query<code>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:
There are many more possibilities using the arguments covered here, but this should give you a taster.
This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time working on personal projects that make his everyday life easier or taking long evening walks with friends.
The above is the detailed content of WP_Query Arguments: Posts, Pages, and Post Types. For more information, please follow other related articles on the PHP Chinese website!