# wp_count_posts()

URL: https://chugunov.pro/api-wordpress/functions/wp_count_posts/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 2.5.0.

## Сигнатура

```php
wp_count_posts( string $type = 'post', string $perm = '' ): stdClass
```

## Описание

Эта функция даёт эффективный способ узнать количество записей заданного типа в блоге. Другой способ — подсчитать количество элементов в get_posts(), но он влечёт значительные накладные расходы. Поэтому при разработке под версии 2.5+ используйте эту функцию.
Параметр $perm проверяет значение 'readable', и если пользователь может читать приватные записи, их количество будет показано для вошедшего пользователя.

## Параметры

- `$type` `string` — необязательный, по умолчанию `'post'`. Тип записи, для которого возвращается количество. Значение по умолчанию 'post'.
- `$perm` `string` — необязательный, по умолчанию `''`. 'readable' или пустое значение.

## Возвращаемое значение

`stdClass`

## Исходный код

Файл: `wp-includes/post.php:3402`

```php
function wp_count_posts( $type = 'post', $perm = '' ) {
	global $wpdb;

	if ( ! post_type_exists( $type ) ) {
		return new stdClass();
	}

	$cache_key = _count_posts_cache_key( $type, $perm );

	$counts = wp_cache_get( $cache_key, 'counts' );
	if ( false !== $counts ) {
		// We may have cached this before every status was registered.
		foreach ( get_post_stati() as $status ) {
			if ( ! isset( $counts->{$status} ) ) {
				$counts->{$status} = 0;
			}
		}

		/** This filter is documented in wp-includes/post.php */
		return apply_filters( 'wp_count_posts', $counts, $type, $perm );
	}

	if (
		'readable' === $perm &&
		is_user_logged_in() &&
		! current_user_can( get_post_type_object( $type )->cap->read_private_posts )
	) {
		// Optimized query uses subqueries which can leverage DB indexes for better performance. See #61097.
		$query = "
			SELECT post_status, COUNT(*) AS num_posts
			FROM (
				SELECT post_status
				FROM {$wpdb->posts}
				WHERE post_type = %s AND post_status != 'private'
				UNION ALL
				SELECT post_status
				FROM {$wpdb->posts}
				WHERE post_type = %s AND post_status = 'private' AND post_author = %d
			) AS filtered_posts
		";
		$args  = array( $type, $type, get_current_user_id() );
	} else {
		$query = "
			SELECT post_status, COUNT(*) AS num_posts
			FROM {$wpdb->posts}
			WHERE post_type = %s
		";
		$args  = array( $type );
	}

	$query .= ' GROUP BY post_status';

	$results = (array) $wpdb->get_results(
		$wpdb->prepare( $query, ...$args ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Placeholders are used in the string contained in the variable.
		ARRAY_A
	);
	$counts  = array_fill_keys( get_post_stati(), 0 );

	foreach ( $results as $row ) {
		$counts[ $row['post_status'] ] = $row['num_posts'];
	}

	$counts = (object) $counts;
	wp_cache_set( $cache_key, $counts, 'counts' );

	/**
	 * Filters the post counts by status for the current post type.
	 *
	 * @since 3.7.0
	 *
	 * @param stdClass $counts An object containing the current post_type's post
	 *                         counts by status.
	 * @param string   $type   Post type.
	 * @param string   $perm   The permission to determine if the posts are 'readable'
	 *                         by the current user.
	 */
	return apply_filters( 'wp_count_posts', $counts, $type, $perm );
}
```

## История изменений

- 2.5.0 — Introduced.

## Связанные

Использует: [`wp_cache_set`](https://chugunov.pro/api-wordpress/functions/wp_cache_set/), [`_count_posts_cache_key`](https://chugunov.pro/api-wordpress/functions/_count_posts_cache_key/), [`wp_count_posts`](https://chugunov.pro/api-wordpress/functions/wp_count_posts/), [`post_type_exists`](https://chugunov.pro/api-wordpress/functions/post_type_exists/), [`get_post_stati`](https://chugunov.pro/api-wordpress/functions/get_post_stati/), [`current_user_can`](https://chugunov.pro/api-wordpress/functions/current_user_can/), [`wp_cache_get`](https://chugunov.pro/api-wordpress/functions/wp_cache_get/), [`is_user_logged_in`](https://chugunov.pro/api-wordpress/functions/is_user_logged_in/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/), [`get_current_user_id`](https://chugunov.pro/api-wordpress/functions/get_current_user_id/), [`get_post_type_object`](https://chugunov.pro/api-wordpress/functions/get_post_type_object/), `wpdb::get_results`, `wpdb::prepare`.
Используется в: [`wp_dashboard_right_now`](https://chugunov.pro/api-wordpress/functions/wp_dashboard_right_now/), [`get_available_post_statuses`](https://chugunov.pro/api-wordpress/functions/get_available_post_statuses/), `WP_Posts_List_Table::get_views`, `WP_Posts_List_Table::prepare_items`.

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/wp_count_posts/
