wp_count_posts()
wp_count_posts( string $type = ‘post’, string $perm = ”…
wp_count_posts( string $type = ‘post’, string $perm = ” )
统计一个帖子类型的帖子数以及用户是否有查看权限。
Count number of posts of a post type and if user has permissions to view.
目录锚点:#说明#参数#源码#笔记
说明(Description)
此函数提供了一种有效的方法来查找blog的类型。另一种方法是计算get_posts()中的项数,但该方法的开销很大。因此,在为2.5+开发时,请改用此函数。$perm参数检查“readable”值,如果用户可以读取私有帖子,它将为登录的用户显示该值。
参数(Parameters)
参数 | 类型 | 说明 |
---|---|---|
$type | (string) | 要检索计数的过帐类型。 |
$perm | (string) | “可读”或为空。 |
源码(Source)
/** * Count number of posts of a post type and if user has permissions to view. * * 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. * * @since 2.5.0 * * @global wpdb $wpdb * * @param string $type Optional. Post type to retrieve count. Default 'post'. * @param string $perm Optional. 'readable' or empty. Default empty. * @return object Number of posts for each status. */ 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 ); }
更新版本 | 源码位置 | 使用 | 被使用 |
---|---|---|---|
2.5.0 | wp-includes/post.php | 17 | 18 |
笔记(Notes)
此函数返回可访问其属性的对象:
类别:WordPress 函数手册、
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。
还没有任何评论,赶紧来占个楼吧!