...

/

Custom Query Arguments

Custom Query Arguments

Learn about the different arguments that can alter custom query results.

We looked at post_type and posts_per_page attributes of the custom query arguments in the previous lesson. In this lesson, we will explore some more query arguments that can be used to order, sort, and compare the query results.

Ordering

By default, the posts are ordered in DESC order to display the most recent posts. We can change this behavior using the order parameter set to ASC (which stands for ascending).

<?php
$args = array(
'order' => 'ASC'
);
Ordering query results

Excluding

We may want to exclude some results from the query. Suppose, we want to display three featured posts followed by a list of the rest of the posts. This means that the featured posts will not be included in the list. We can achieve this by setting up a query to display the featured posts followed by another query to display the rest of the posts.

The code below shows an array of arguments which sets the number of posts to 3. This array is used to create the $featuredPosts query object. The $featuredPostID array stores the IDs of the posts inside the while loop. To keep things simple, only the titles of the posts are displayed in the loop.

<?php
$args = array(
'posts_per_page' => 3;
);
$featuredPosts = new WP_Query($args);
$featuredPostId = array();
while($featuredPosts->have_posts()){
$featuredPosts->the_post(); ?>
<li><?php the_title(); ?></li>
<?php
$featuredPostsId[] = get_the_Id();
}
wp_reset_query();
?>
Excluding some posts from the query

After running the first query, it is important to reset the query data. Next, we will create another custom query. This time the array of arguments contains the post__not_in parameter which is set to the $featuredPostsId array (populated by the previous query). The $otherPosts ...