count_many_users_posts() │ WP 3.0.0
Возвращает количество записей для нескольких указанных пользователей (указываются ID).
Если нужно получить количество записей одного пользователя, используйте count_user_posts().
Возвращает
Массив. Массив с данными о количество записей каждого пользователя.
Использование
$users_posts_count = count_many_users_posts( $users );
- $users(массив) (обязательный)
- Массив ID пользователей, количество записей которых нужно получить.
Примеры
#1 Как получить количество постов пользователей: 1, 3, 9, 10:
$users = array( 1, 141 );
$counts = count_many_users_posts( $users );
echo 'Постов опубликованных пользователем 141: ' . $counts[141];
// Получим: Постов опубликованных пользователем 3: 15
print_r( $counts );
/*
Array (
[1] => 157
[141] => 15
)
*/
Заметки
- Global. wpdb.
$wpdb WordPress database abstraction object.
Список изменений
| С версии 3.0.0 |
Введена. |
| С версии 6.9.0 |
The results are now cached. |
Код count_many_users_posts() count many users posts
WP 7.0
function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
global $wpdb;
if ( empty( $users ) || ! is_array( $users ) ) {
return array();
}
/**
* Filters whether to short-circuit performing the post counts.
*
* When filtering, return an array of posts counts as strings, keyed
* by the user ID.
*
* @since 6.8.0
*
* @param string[]|null $count The post counts. Return a non-null value to short-circuit.
* @param int[] $users Array of user IDs.
* @param string|string[] $post_type Single post type or array of post types to check.
* @param bool $public_only Whether to only return counts for public posts.
*/
$pre = apply_filters( 'pre_count_many_users_posts', null, $users, $post_type, $public_only );
if ( null !== $pre ) {
return $pre;
}
// Cleanup the users array. Remove duplicates and sort for consistent ordering.
$users = array_unique( array_filter( array_map( 'intval', $users ) ) );
sort( $users );
// Cleanup the post type argument. Remove duplicates and sort for consistent ordering.
$post_type = array_unique( (array) $post_type );
sort( $post_type );
$userlist = implode( ',', $users );
$where = get_posts_by_author_sql( $post_type, true, null, $public_only );
$query = "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author";
$cache_key = 'count_many_users_posts:' . md5( $query );
$cache_salts = array( wp_cache_get_last_changed( 'posts' ), wp_cache_get_last_changed( 'users' ) );
$count = wp_cache_get_salted( $cache_key, 'post-queries', $cache_salts );
if ( false === $count ) {
$result = $wpdb->get_results( $query, ARRAY_N );
$count = array_fill_keys( $users, 0 );
foreach ( $result as $row ) {
$count[ $row[0] ] = $row[1];
}
wp_cache_set_salted( $cache_key, $count, 'post-queries', $cache_salts, HOUR_IN_SECONDS );
}
return $count;
}
Cвязанные функции