如何在 WP_Query 中按日期排序?

how to order by date in WP_Query ?

我试过这种方式,但是 orderbyorder 在 WP_Query class[=12 上不起作用=]

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

总是 return orderby=> 'menu_order'order='ASC'.

注意:如果我在 url 中使用参数作为 orderby=date&order=ASC 那么它工作正常但我需要作为 WP_Query 的参数。

提前致谢

根据文档显示 post 按日期排序你应该使用 date。(但无论如何默认是日期)

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

     'orderby'=> 'date', 

要显示与特定类型关联的 post,这些是有效的 types.So,您必须使用其中一个

  • 'post' - 一个 post.
  • 'page' - 一页。
  • 'revision' - 修订。
  • 'attachment' - 附件。而默认 WP_Query post_status 是 'publish',附件的默认 post_status 为 'inherit'。 这意味着除非您也明确表示,否则不会返回任何附件 将 post_status 设置为 'inherit' 或 'any'。 (见下文 post_status)
  • 'nav_menu_item' - 导航菜单项
  • 'any' - 检索除修订和类型之外的任何类型 'exclude_from_search' 设为真。
  • 自定义 Post 类型(例如电影)

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

您可以在 WP_Query() 中为 orderby 设置多个参数。如日期标题menu_order

这里是Order & Orderby Parameters

试试这个例子

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

这个例子在 WP Version_4.x

中对我来说工作正常