2016-06-07 88 views
1

需要获取发布在特定自定义帖子类型(CTP)中的最后5个用户。由于我似乎无法找到一个WordPress功能来这样做,我正在尝试编写一个自定义查询。SQL:Wordpress用户在其最新发布日期(CPT)之前订购

到目前为止,我已经得到这个以获得最后五个和他们的帖子数量(仅my_custom_type),但它还没有工作。
这里是我的查询:

SELECT *, count(ID) 
FROM wp_posts 
WHERE post_type = 'my_custom_type' 
GROUP BY post_author 
ORDER BY post_author DESC LIMIT 5 

我想跳过管理员(post_author = 1)。

我该如何做到这一点?

谢谢。

回答

1

您需要通过IDpost_datepost_author排除管理员post_author>1订购更好:

SELECT * 
FROM `wp_posts` 
WHERE `post_author` != 1 
AND `post_status` = 'publish' 
AND `post_type` = 'my_custom_type' 
GROUP BY `post_author` 
ORDER BY `ID` DESC, `post_author` ASC LIMIT 5 

更新:

您将获得现在最后5名作者名单由方兴未艾日期排序( ASC'ID')有'已发布'帖子(自定义帖子类型='my_custom_type'),不包括管理员(用户ID = 1)。最后,每位作者的总职位数量。

下面是查询:

select t1.*, t2.author_count 
from `wp_posts` t1 
inner join (
    select max(`ID`) as `ID`, `post_author`, count(1) as author_count 
    from `wp_posts` 
    where `post_author` != '1' 
    and `post_status` = 'publish' 
    and `post_type` = 'my_custom_type' 
    group by `post_author` 
) t2 on t1.`ID` = t2.`ID` and t1.`post_author` = t2.`post_author` 
order by t1.`ID` desc limit 5 

author_count是生成列计数总'published'帖子,具有'post_type' = 'my_custom_type'为每个选定的作者。

根据this answer

+0

谢谢你的回答,我认为它应该是'ORDER BY'post_date'',对吧?以便在其最新帖子的日期前订购。它*不适用于'GROUP BY'post_author''时的工作。如果与'GROUP BY'post_author''一起使用,会扰乱订单。但是如果没有使用'GROUP BY'post_author'',并且用户恰好最近发布了两次,他也会在列表结果中出现两次。请帮忙! – karlosuccess

+0

如果我不使用“GROUP BY”和“COUNT(ID)”,它就像一个魅力。但是,正如我所提到的,如果用户最近发布了两次,他也会在列表结果中出现两次。另外,如果可能的话,我想获得用户总帖子(使用COUNT()或类似的)。感谢您的帮助 – karlosuccess

+0

我需要列出由最后一次CTP帖子排序的5位用户。这是没有'GROUP BY'post_author''工作。但是如果我们不使用它,如果用户最近发布了两次,他也会在列表结果中出现两次。另外,如果可能的话,我想获得用户总帖子(使用COUNT()或类似的)。 – karlosuccess