简体   繁体   中英

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

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

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 (eg movies)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM