wp_count_posts

函式
wp_count_posts ( $type = 'post', $perm = '' )
引數
  • (string) $type Optional. Post type to retrieve count. Default 'post'.
    Required:
    Default: 'post'
  • (string) $perm Optional. 'readable' or empty. Default empty.
    Required:
    Default: (empty)
返回值
  • (stdClass) Number of posts for each status.
定義位置
相關方法
wp_count_siteswp_count_termswp_count_commentswp_untrash_postcount_user_posts
引入
2.5.0
棄用
-

wp_count_posts: 這是一個返回特定文章型別的文章數量的函式。它可以用來獲得文章型別的概述,並跟蹤文章的數量。

計算某個文章型別的文章數量,以及使用者是否有檢視的許可權。

這個函式提供了一個有效的方法來查詢一個部落格的文章型別的數量。另一種方法是在get_posts()中計算專案的數量,但這種方法有很多開銷。因此,在為2.5以上版本開發時,請使用這個函式來代替。

$perm引數檢查’可讀’值,如果使用者可以閱讀私人文章,它將為已登入的使用者顯示。

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 );
	}

	$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' );

	/**
	 * Modifies returned 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 );
}

常見問題

FAQs
檢視更多 >