Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save carlaizumibamford/2cc47f8744b519484fc12f834c11ee53 to your computer and use it in GitHub Desktop.
Save carlaizumibamford/2cc47f8744b519484fc12f834c11ee53 to your computer and use it in GitHub Desktop.
Display posts sorted by post ‘title’ in a descending order:
$args = array(
'orderby' => 'title',
'order' => 'DESC',
);
$query = new WP_Query( $args );
Display posts sorted by ‘menu_order’ with a fallback to post ‘title’, in a descending order:
$args = array(
'orderby' => 'menu_order title',
'order' => 'DESC',
);
$query = new WP_Query( $args );
Display one random post:
$args = array(
'orderby' => 'rand',
'posts_per_page' => '1',
);
$query = new WP_Query( $args );
Display posts ordered by comment count (popularity):
$args = array(
'orderby' => 'comment_count'
);
$query = new WP_Query( $args );
Display posts with ‘Product’ type ordered by ‘Price’ custom field:
$args = array(
'post_type' => 'product',
'orderby' => 'meta_value_num',
'meta_key' => 'price',
);
$query = new WP_Query( $args );
Display pages ordered by ‘title’ and ‘menu_order’. (title is dominant):
$args = array(
'post_type' => 'page',
'orderby' => 'title menu_order',
'order' => 'ASC',
);
$query = new WP_Query( $args );
Display pages ordered by ‘title’ and ‘menu_order’ with different sort orders (ASC/DESC) (available since version 4.0):
$args = array(
'orderby' => array( 'title' => 'DESC', 'menu_order' => 'ASC' )
);
$query = new WP_Query( $args );
Related article: A more powerful ORDER BY in WordPress 4.0.
Mulitiple orderby/order pairs
$args = array(
'orderby' => array( 'meta_value_num' => 'DESC', 'title' => 'ASC' ),
'meta_key' => 'age'
);
$query = new WP_Query( $args );
‘orderby’ with ‘meta_value’ and custom post type
Display posts of type ‘my_custom_post_type’, ordered by ‘age’, and filtered to show only ages 3 and 4 (using meta_query).
$args = array(
'post_type' => 'my_custom_post_type',
'meta_key' => 'age',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'age',
'value' => array( 3, 4 ),
'compare' => 'IN',
),
),
);
$query = new WP_Query( $args );
Collapse full source code
‘orderby’ with multiple ‘meta_key’s
If you wish to order by two different pieces of postmeta (for example, City first and State second), you need to combine and link your meta query to your orderby array using ‘named meta queries’. See the example below:
$q = new WP_Query( array(
'meta_query' => array(
'relation' => 'AND',
'state_clause' => array(
'key' => 'state',
'value' => 'Wisconsin',
),
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'city_clause' => 'ASC',
'state_clause' => 'DESC',
),
) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment