当我想显示一篇文章的评论数量时,我在循环中,建议使用哪个函数?
get_post_field( \'comment_count\', get_the_ID() )
或
get_comments_number()
这是
get_post_field
功能:
/**
* Retrieve data from a post field based on Post ID.
*
* Examples of the post field will be, \'post_type\', \'post_status\', \'post_content\',
* etc and based off of the post object property or key names.
*
* The context values are based off of the taxonomy filter functions and
* supported values are found within those functions.
*
* @since 2.3.0
*
* @see sanitize_post_field()
*
* @param string $field Post field name.
* @param int|WP_Post $post Post ID or post object.
* @param string $context Optional. How to filter the field. Accepts \'raw\', \'edit\', \'db\',
* or \'display\'. Default \'display\'.
* @return string The value of the post field on success, empty string on failure.
*/
function get_post_field( $field, $post, $context = \'display\' ) {
$post = get_post( $post );
if ( !$post )
return \'\';
if ( !isset($post->$field) )
return \'\';
return sanitize_post_field($field, $post->$field, $post->ID, $context);
}
还有这个id
get_comments_number
:
/**
* Retrieve the amount of comments a post has.
*
* @since 1.5.0
*
* @param int|WP_Post $post_id Optional. Post ID or WP_Post object. Default is global $post.
* @return int The number of comments a post has.
*/
function get_comments_number( $post_id = 0 ) {
$post = get_post( $post_id );
if ( ! $post ) {
$count = 0;
} else {
$count = $post->comment_count;
$post_id = $post->ID;
}
/**
* Filter the returned comment count for a post.
*
* @since 1.5.0
*
* @param int $count Number of comments a post has.
* @param int $post_id Post ID.
*/
return apply_filters( \'get_comments_number\', $count, $post_id );
}
我可以看出他们有不同之处,但我不知道哪一个更好(如果有的话。也许他们都可以)。