Im trying to order by post_count DESC but custom_post_type not working
function post_count_type($role, $number) {
$args = array(
'post_type' => array( 'custom_post_type' ),
'orderby' => 'post_count',
'order' => 'DESC',
'role' => $role,
'number' => $number
);
$users = get_users( $args );
$the_query = new WP_Query( $args );
foreach ($users as $user) {
echo 'html here...';
}}
My function work for post_type : POST but not for custom post_type. Sorry for my english.
Im trying to order by post_count DESC but custom_post_type not working
function post_count_type($role, $number) {
$args = array(
'post_type' => array( 'custom_post_type' ),
'orderby' => 'post_count',
'order' => 'DESC',
'role' => $role,
'number' => $number
);
$users = get_users( $args );
$the_query = new WP_Query( $args );
foreach ($users as $user) {
echo 'html here...';
}}
My function work for post_type : POST but not for custom post_type. Sorry for my english.
Share Improve this question edited Nov 4, 2019 at 10:25 mems asked Nov 3, 2019 at 21:26 memsmems 7312 bronze badges 2 |1 Answer
Reset to default 7You are using wrong approach
You are using the wrong approach for what you are trying to achieve. You are using the same arguments for both WP_Query
and WP_User_Query
(get_users
eventually translates to WP_User_Query
). The problem is that WP_Query
doesn't support orderby
parameter post_count
as one post is always equal to one post and WP_User_Query
doesn't support post_type
as the user doesn't have post type assigned to themselves.
This can't be achieved using standard functions
In WP_User_Query
it's hardcoded that for user posts count, it looks only for post_type post
. To achieve what you are trying to, you need to write a custom database query.
A custom solution
A standalone function to achieve this might look like this (please note I haven't tested it so there might be a SQL typos or smth).
function get_users_by_post_count( $post_type = 'post' ) {
global $wpdb;
$users = $wpdb->get_results(
$wpdb->prepare(
"SELECT {$wpdb->users}.ID, p.post_count
FROM {$wpdb->users}
LEFT JOIN (
SELECT post_author, COUNT(*) AS post_count
FROM {$wpdb->posts} WHERE post_type = %s
GROUP BY post_author
) p ON {$wpdb->users}.id = p.post_author
ORDER BY p.post_count",
$post_type
)
);
return $users;
}
To use it simply call it like:
$users = get_users_by_post_count( 'custom_post_type' );
if ( ! empty( $users ) ) {
foreach ( $users as $user ) {
// there you have user ID and post_count
echo $user->ID . ' has ' . $user->post_count . ' posts';
}
}
post_count
? Each post should equate to 1 post, categories would have multiple posts assigned to there where apost_count
would make sense. Would you happen to mean the order that you can assign under Page Attributes metabox? – Howdy_McGee ♦ Commented Nov 3, 2019 at 22:16