我想按作者角色查询帖子。 并根据角色对帖子做一些事情。
我知道我们可以通过 get_posts 或 WP_query 获取帖子,问题是没有根据作者角色对帖子进行排序的参数。 或者,我们也可以将 get_users 和 get_posts 组合在一起,像这样
$users = get_users(array(role => 'author'));
foreach($users as $user){
//here we can use get_posts to query the posts by the $user->ID
} .....
这样做太笨拙了。 我想知道是否还有其他方法可以根据角色查询帖子,也许是 SQL 查询?
我之前并没有真正搞砸过自定义帖子查询,但这是我尝试的解决方案:
function get_posts_by_author_role($role) {
global $wpdb;
return $wpdb->get_results( "SELECT p.* FROM {$wpdb->posts} p, {$wpdb->usermeta} u"
." WHERE p.post_type="post""
." AND p.post_status="publish""
." AND u.user_id = p.`post_author`"
." AND u.meta_key = 'wp_capabilities'"
." AND u.meta_value LIKE '%\"{$role}\"%'" );
}
仅当作者具有指定的角色时,此函数才会返回帖子。 它已经过测试,可以在我本地安装的 3.4 上运行,但如果您对它有任何问题,请告诉我。
我希望这有帮助。
用法示例:
$posts = get_posts_by_author_role('author');
foreach($posts as $post) echo $post->post_title, '<br />';
尝试这个
创建一个函数来改变查询的 where 子句:
function authors_where_filter( $where ) {
global $wpdb;
$ids = get_users(array('role' => 'author' ,'fields' => 'ID'));
$where .= " AND post_author IN ($ids)";
return $where;
}
然后在您查询之前将其挂钩:
add_filter('posts_where','authors_where_filter');
$all_posts = new WP_Query(array('posts_per_page' => -1 .....
remove_filter('posts_where');
并且您应该在单个查询中获取作者用户的所有帖子(实际上有两个用于获取用户,另一个用于获取帖子)
