简体   繁体   English

如何在 WP_Query 中按日期排序?

[英]how to order by date in WP_Query ?

I have tried this way but orderby and order not working on WP_Query class我已经尝试过这种方式,但是orderbyorder在 WP_Query 类上不起作用

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

always it return orderby=> 'menu_order' and order='ASC' .它总是返回orderby=> 'menu_order'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.注意:如果我在 url 中使用 param 作为orderby=date&order=ASC那么它工作正常但我需要作为 WP_Query 的参数。

Thanks in advance提前致谢

You can set multiple parameters for orderby in your WP_Query() .您可以在WP_Query() 中orderby设置多个参数。 Like date , title , menu_order etc.datetitlemenu_order等。

Here is the Order & Orderby Parameters这是Order & Orderby 参数

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这个例子在 WP Version_4.x 中对我来说正常工作

According to the docs to show posts ordered by date you should use date .(But the default is date anyway)根据显示按日期排序的帖子的文档,您应该使用date 。(但无论如何默认为 date )

"orderby (string | array) - Sort retrieved posts by parameter. Defaults to 'date (post_date)'. One or more options can be passed." "orderby (string | array) - 按参数对检索到的帖子进行排序。默认为 'date (post_date)'。可以传递一个或多个选项。"

     'orderby'=> 'date', 

To show posts associated with certain type these are the valid types.So you must use on of them要显示与特定类型相关的帖子,这些是有效类型。所以你必须使用它们

  • 'post' - a post. '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'.虽然默认的 WP_Query post_status 是“publish”,但附件的默认 post_status 是“inherit”。 This means no attachments will be returned unless you also explicitly set post_status to 'inherit' or 'any'.这意味着不会返回任何附件,除非您还明确将 post_status 设置为 'inherit' 或 'any'。 (See post_status, below) (请参阅下面的 post_status)
  • 'nav_menu_item' - a navigation menu item 'nav_menu_item' - 导航菜单项
  • 'any' - retrieves any type except revisions and types with 'exclude_from_search' set to true. 'any' - 检索除修订版和类型之外的任何类型,其中 'exclude_from_search' 设置为 true。
  • Custom Post Types (eg movies)自定义帖子类型(例如电影)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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