функция since 2.5.0

wp_count_posts()

Проверено на WordPress 6.9, обновлено Источник: WordPress Developer Resources.

Сигнатура

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

Описание

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

Оригинал (английский)

This function provides an efficient method of finding the amount of post’s type a blog has. Another method is to count the amount of items in get_posts() , but that method has a lot of overhead with doing so. Therefore, when developing for 2.5+, use this function instead.

The $perm parameter checks for ‘readable’ value and if the user can read private posts, it will display that for the user that is signed in.

Параметры

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

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

stdClass

Исходный код

wp-includes/post.php:3402

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.

Что будем искать? Например,Продвижение

Этот сайт использует куки-файлы. Оставаясь на сайте, Вы соглашаетесь на их использование. Для получения дополнительной информации, пожалуйста, ознакомьтесь с политикой в отношении персональных данных.