how to order by date in WP_Query ?

I have tried this way but orderby and order not working on WP_Query class

$posts = new WP_Query(
array( 'post_type'=> 'block_code', 'orderby'=> 'post_date', 'order' => 'DESC' )
);

always it return orderby=> 'menu_order' and order='ASC'.

Note: if i use param in url as orderby=date&order=ASC then it works fine But i need as argument of WP_Query.

Thanks in advance

2 Answers

You can set multiple parameters for orderby in your WP_Query(). Like date,title,menu_order etc.

Here is the Order & Orderby Parameters

Try this example

$params = array( 'post_type' =>'block_code', 'orderby' => array( 'date' =>'DESC', 'menu_order'=>'ASC', /*Other params*/ )
);
$query = new WP_Query($params);

This example working properly for me in WP Version_4.x

2

According to the docs to show posts ordered by date you should use date.(But the default is date anyway)

"orderby (string | array) - Sort retrieved posts by parameter. Defaults to 'date (post_date)'. One or more options can be passed."

 'orderby'=> 'date', 

To show posts associated with certain type these are the valid types.So you must use on of them

  • 'post' - a post.
  • 'page' - a page.
  • 'revision' - a revision.
  • 'attachment' - an attachment. Whilst the default WP_Query post_status is 'publish', attachments have a default post_status of 'inherit'. This means no attachments will be returned unless you also explicitly set post_status to 'inherit' or 'any'. (See post_status, below)
  • 'nav_menu_item' - a navigation menu item
  • 'any' - retrieves any type except revisions and types with 'exclude_from_search' set to true.
  • Custom Post Types (e.g. movies)
9

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like