2016-06-07 38 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