计算帖子类型的帖子数量以及用户是否有权查看。

原型

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

描述

此功能提供了一种查找博客所具有的帖子类型数量的有效方法。另一种方法是计算get_posts()中的项目数量,但是这样做会产生很多开销。因此,在开发2.5时,请改用此功能。

参数

$type (string) (Optional)  发布类型以检索计数。

$perm (string) (Optional)  ‘可读’或空。

返回值

(object)  每个状态的帖子数。

源文件

路径:wp-includes/post.php

<?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 ) {
		/** This filter is documented in wp-includes/post.php */
		return apply_filters( 'wp_count_posts', $counts, $type, $perm );
	}
	$query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
	if ( 'readable' == $perm && is_user_logged_in() ) {
		$post_type_object = get_post_type_object($type);
		if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
			$query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
				get_current_user_id()
			);
		}
	}
	$query .= ' GROUP BY post_status';
	$results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), 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' );
	/**
	 * Modify returned post counts by status for the current post type.
	 *
	 * @since 3.7.0
	 *
	 * @param object $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 );
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_count_posts/