我遇到了一个小问题。我正试图通过一个自定义的元字段获得最新的12篇文章。在这12个帖子中,我想在发布日期前订购。因此,首先我使用一个自定义的元字段提取12篇帖子,并命令它们通过元字段查找最新的帖子。一旦我有了它们,然后我想用最新的帖子重新订购。
这是我当前的代码,我不知道如何在一个查询中放入两个订单号。。。
$recentEpisodes12 = new WP_Query(array(
'posts_per_page' => 12,
'post_type' => 'post',
'meta_key' => 'air_date',
'order' => 'DESC',
'orderby' => 'meta_value_num',
'meta_query' => array(
array(
'key' => 'air_date',
),
array(
'key' => 'already_aired',
'value' => 'yes',
'compare' => '='
)
),
));
在WordPress 4.2及更高版本中,通过一个或多个自定义字段进行排序变得更加容易。有关示例,请参见此链接:https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
您甚至可以通过向orderby传递一个数组来订购一列ASC和另一列DESC:
'orderby' => array(
'city_clause' => 'ASC',
'state_clause' => 'DESC',
),
根据Codex,您只需要用一个空格将它们分开:
多个"orderby"值
显示按"title"和"menu_order"排序的页面。(标题为显性):
$query = new WP_Query( array( 'post_type' => 'page', 'orderby' => 'title menu_order', 'order' => 'ASC' ) );
在你的情况下,这看起来像:
'orderby' => 'meta_value_num date'
编辑:好吧,你似乎在尝试做一些更复杂的事情。这就是我对它的解释,如果我错了,纠正我的错误:
- 按
air_date
排序(按降序排列,最新优先) - 根据
air_date
,只保留最新的12项 - 通过
date
对生成的12个项目进行排序
orderby
的基本功能是:
- 按
air_date
订购 - 如果任何项目具有相同的
air_date
值,请按date
排序 - 只保留前12项
不同之处在于,您只想通过air_date
来区分,而orderby
的正常使用则使用这两个标准来确定结果中的项目。
不过,我不知道有什么简单的方法可以解决这个问题。但是,由于您只想更改结果项的显示顺序,因此您可以自己对它们进行排序。您可以使用get_posts
而不是WP_Query
,并使用PHP的usort
对结果数组进行排序
$posts = get_posts(...);
usort($posts, '__sort_by_date_desc');
function __sort_by_date_desc($a, $b) {
// Make timestamps from MySQL datetime values
$a_date = mysql2date('U', $a->post_date);
$b_date = mysql2date('U', $b->post_date);
// Descending order, swap these for ascending
return $b_date - $a_date;
}
如果你想在发布日期前订购,为什么需要一个元字段?一旦你通过元值获得了12篇最新的帖子,air_date
是否与发布日期有所不同?
值得注意的是:posts_per_page
并没有限制退货总数。它只是告诉WordPress何时拆分到一个新页面。
像这样的东西应该基于你在原始帖子中描述的内容。
// Post Criteria
$post_criteria = array(
'posts_per_page' => 12, // Don't paginate until after 12 posts
'orderby' => 'post_date', // Order by post date
'order' => 'DESC', // Order them reverse chronologically (ie. get the newest first)
'meta_key' => 'air_date', // Only get posts with this meta key
'meta_value' => 'meta_value_num', // And this meta value (only needed if you have multiple possible values for the meta key and just want one)
'post_type' => 'post', // Only get posts
'post_status' => 'publish'); // Only get posts that are published (ie. no drafts, etc.)
// Get posts matching criteria
$posts = get_posts( $post_criteria );
// Discard posts after the 12th one
$posts = array_slice($posts, 0, 12);
// If you wanted to reverse them to display
// chronologically, uncomment this variable.
# $posts = array_reverse($posts);
// For each post
foreach ($posts as $post) {
// Basic variables
// See a full list here: http://codex.wordpress.org/Function_Reference/get_post#Return
$id = $post->ID;
$title = $post->post_title;
$url = get_permalink($id);
$content = $post->post_content;
// Do stuff with the posts here.
}