問題描述
我看到可以按使用者擁有的帖子數排序使用者查詢,但是可以從結果中排除零個帖子的使用者嗎?在 Wp_User_Query 類中,有一個 pre_user_query 操作,但是查詢字串是一個很大的弱點,所以我不知道我想在這裡使用什麼樣的過濾器操作。
最佳解決方案
我已經提出了 2 個解決方案。
解決方案 1 – foreach 迴圈並驗證每個使用者
這是基於 @ GhostToast 的解決方案,但更新的 WordPress 功能
//new query with default args
$author_query = new WP_User_Query();
// Get the results
$authors = $author_query->get_results();
if( $authors ) {
foreach( $authors as $author ) {
if ( count_user_posts( $author->id ) >= 1 ) {
echo $author->display_name . '</br>';
}
}
} else {
echo "no users found";
}
解決方案 2 – 花式褲 pre_user_query 動作
當我在 WP_User_Query 類中找到 pre_user_query 操作時,我釋出了我的問題,這是我想的。如果您以 post_count 作為 orderby 引數傳遞,那麼我自己從未想到的一些奇特的 SQL 查詢就可以一起加入到正確的表中。所以我做的是複製該連線語句並將其新增到我自己的。如果我可以在新增它之前檢查它的存在,這可能會更好 – 也許我將來會使用字串匹配。但是現在,由於我是一個設定查詢的人,所以我知道它不在,我也不用擔心。所以程式碼原來是這樣的:
function authors_with_posts( $query ) {
if ( isset( $query->query_vars['query_id'] ) && 'authors_with_posts' == $query->query_vars['query_id'] ) {
$query->query_from = $query->query_from . ' LEFT OUTER JOIN (
SELECT post_author, COUNT(*) as post_count
FROM wp_posts
WHERE post_type = "post" AND (post_status = "publish" OR post_status = "private")
GROUP BY post_author
) p ON (wp_users.ID = p.post_author)';
$query->query_where = $query->query_where . ' AND post_count > 0 ';
}
}
add_action('pre_user_query','authors_with_posts');
然後用它
$args = ( array( 'query_id' => 'authors_with_posts' ) );
$author_query = new WP_User_Query( $args );
query_id 引數的想法來自 「WP_User_Class 簡介」
哪個也是 WP_User_Query 的非常好的參考
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。