How to Use orderby in WP_Query in WordPress
Use the
orderby parameter in WP_Query to sort posts by fields like date, title, or custom fields. Pass orderby with the field name and optionally order with ASC or DESC to control sorting direction.Syntax
The orderby parameter in WP_Query defines how posts are sorted. You can use values like date, title, meta_value (for custom fields), and more. The order parameter controls ascending (ASC) or descending (DESC) order.
Example parameters:
orderby => 'date'- Sort by post dateorderby => 'title'- Sort alphabetically by titleorderby => 'meta_value'- Sort by a custom field valueorder => 'ASC'- Sort ascendingorder => 'DESC'- Sort descending
php
$args = array(
'post_type' => 'post',
'orderby' => 'date', // or 'title', 'meta_value', etc.
'order' => 'DESC' // or 'ASC'
);
$query = new WP_Query($args);Example
This example shows how to query posts ordered by title in ascending order.
php
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => 5
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<h2>' . get_the_title() . '</h2>';
}
wp_reset_postdata();
} else {
echo 'No posts found.';
}
?>Output
<h2>Alpha Post</h2><h2>Beta Post</h2><h2>Gamma Post</h2><h2>Omega Post</h2><h2>Zeta Post</h2>
Common Pitfalls
Common mistakes include:
- Not setting
orderwhen usingorderby, which defaults toDESC. - Using
orderby => 'meta_value'without specifyingmeta_key, so WordPress doesn't know which custom field to sort by. - Trying to order by a custom field without setting the correct
meta_type(likeNUMERICfor numbers).
php
<?php // Wrong: missing meta_key $args_wrong = array( 'post_type' => 'post', 'orderby' => 'meta_value', 'order' => 'ASC' ); // Right: specify meta_key and meta_type $args_right = array( 'post_type' => 'post', 'meta_key' => 'price', 'orderby' => 'meta_value_num', 'order' => 'ASC' ); ?>
Quick Reference
| Parameter | Description | Example Values |
|---|---|---|
| orderby | Field to sort posts by | 'date', 'title', 'meta_value', 'meta_value_num', 'rand' |
| order | Sort direction | 'ASC' (ascending), 'DESC' (descending) |
| meta_key | Custom field key when sorting by meta_value | 'price', 'rating' |
| posts_per_page | Number of posts to return | 5, 10, -1 (all) |
Key Takeaways
Always use the
orderby parameter in WP_Query to control post sorting.Pair
orderby => 'meta_value' with meta_key to sort by custom fields.Set
order to ASC or DESC to define sorting direction.For numeric custom fields, use
orderby => 'meta_value_num' and specify meta_key.Test queries to ensure sorting works as expected and reset post data after custom loops.