Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 727
tarikul05 Avatar asked Jul 26 '16 10:07

tarikul05


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

like image 118
Sumon Sarker Avatar answered Oct 24 '22 10:10

Sumon Sarker


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)

https://codex.wordpress.org/Class_Reference/WP_Query

like image 2
George Pant Avatar answered Oct 24 '22 09:10

George Pant