The WP_Query is a very powerful WordPress function used to make very specific WordPress loops based on a large number options.
The WP_Query function is placed before the loop. A nice aspect of this function is that all you have to do is place it before the loop and you don’t have to change anything about the loop itself.
Here are a few of the most common WP_Query options:
author
– Filters loop by author idauthor_name
– Filters author by user_nicenamecat
– Filters loop by category idcategory_name
– Filters loop by category slugtag
– Filters loop by tag slugp
– Filters loop by page or post idname
– Filters loop by post slugpagename
– Filters loop by page slugpage_id
– Filters loop by page ifpost_parent
– Filters loop by id of parent pagepost_type
– Filters loop by post type, including custom post typesposts_per_page
– Determines how many posts are looped throughoffset
– Determines how many posts to offset the loop byorder
– Determines whether the posts display in ascending or descending orderorderby
– Filters what factor the posts are sorted by. Default is date, but can be changed to things like title or authoryear
– Filters loop by posts in a given yearmonthnum
– Filters loop by a month numner. i.e. 1 = Januaryday
– Filters loop by a specific day of the month
Usually all of the parameters are passed to the WP_Query function as an array.
Here is an example of using the WP_Query function to display the content for a specific page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $args = array( 'pagename' => 'about-us' ); $the_query = new WP_Query($args); if ($the_query->have_posts()): while ($the_query->have_posts()): $the_query->the_post(); ?> <h1><?php the_title(); ?></h1> <?php the_excerpt(); endwhile; else: ?> <p>Sorry, there are no posts to display</p> <?php endif; ?> |
For a more complex example, we can look at how to display all of the posts published by a specific author in a custom post type called notes. We will also filter the loop so that it orders the posts by the title and only displays workshops published in the year 2012.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php $args = array( 'author_name' => 'onote', 'orderby' => 'title', 'post_type' => 'notes' 'year' => 2010 ); $the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h1><?php the_title() ;?></h1> <?php the_excerpt(); ?> <?php endwhile; else: ?> <p>Sorry, there are no posts to display</p> <?php endif; ?> |