我为帖子设置了一个特殊的“position”元字段,可以在0到37之间。0被忽略,其他任何数字都可以是介于1和37之间(包括1和37)。但这当然意味着多个帖子可以有相同的数字。
现在我只想从这些副本中选择最新的条目,但是,我没有任何运气。以下是我为实现目前目标所采用的方法:
add_action( \'pre_get_posts\', \'foo_pre_get_posts\' );
function foo_pre_get_posts( $query ) {
if (!is_admin() && is_home() && is_a( $query, \'WP_Query\' ) && $query->is_main_query() ) {
$query->set( \'meta_key\', \'_position\' );
$query->set( \'posts_per_page\', 37 );
$query->set( \'meta_value\', \'0\' );
$query->set( \'meta_compare\', \'>\' );
$query->set( \'paged\', 1 );
}
}
// order the stuff on meta value and then post date since pre_get_posts can\'t do it.
add_filter("posts_orderby", "foo_posts_orderby");
function foo_posts_orderby( $orderby) {
if (!is_admin() && is_home()) {
return "wp_postmeta.meta_value+0 ASC, wp_posts.post_date DESC";
}
return $orderby;
}
add_filter("posts_groupby", "foo_posts_groupby");
function foo_posts_groupby( $orderby) {
if (!is_admin() && is_home()) {
return "wp_posts.ID, wp_postmeta.meta_value";
}
return $orderby;
}
生成的SQL:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
WHERE 1=1 AND
wp_posts.post_type = \'post\' AND
(wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\') AND
( (
wp_postmeta.meta_key = \'_position\' AND
CAST(wp_postmeta.meta_value AS CHAR) > \'0\'
) )
GROUP BY wp_posts.ID, wp_postmeta.meta_value
ORDER BY wp_postmeta.meta_value+0 ASC, wp_posts.post_date DESC LIMIT 0, 31
我试过团员,但没用,我试过
DISTINCT
直接在phpMyAdmin中(当然是复制生成的SQL),同样没有用。
我得到的结果是:
[ ID ] [ position ] [ date ]
1 1 12/08/2012
4 1 07/08/2012
5 1 06/08/2012
6 2 08/08/2012
9 2 07/08/2012
8 5 09/08/2012
注:这只是测试数据
如何使其仅根据位置选择第一个选项,例如:
[ ID ] [ position ] [ date ]
1 1 12/08/2012
6 2 08/08/2012
8 5 09/08/2012
谢谢!
最合适的回答,由SO网友:Hosh Sadiq 整理而成
我发现我可以把它分组wp_postmeta.meta_value
自行(无需wp_posts.ID
) 成功了!因此,它最终变成如下。PHP:
add_filter("posts_groupby", "foo_posts_groupby");
function foo_posts_groupby( $groupby) {
if (!is_admin() && is_home()) {
return "wp_postmeta.meta_value";
}
return $groupby;
}
SQL变成:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
WHERE 1=1 AND
wp_posts.post_type = \'post\' AND
(wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\') AND
( (
wp_postmeta.meta_key = \'_position\' AND
CAST(wp_postmeta.meta_value AS CHAR) > \'0\'
) )
GROUP BY wp_postmeta.meta_value
ORDER BY wp_postmeta.meta_value+0 ASC, wp_posts.post_date DESC LIMIT 0, 31
工作得很有魅力!