_close_comments_for_old_posts()
云策文档标注
概述
_close_comments_for_old_posts() 是一个 WordPress 函数,用于在查询时自动关闭旧文章的评论,无需额外数据库查询。它通过 the_posts 钩子触发,根据设置的天数和文章类型条件动态修改文章对象的评论状态。
关键要点
- 函数在 the_posts 钩子中调用,处理文章数组和查询对象,以实时关闭旧文章的评论。
- 通过 get_option() 获取 'close_comments_for_old_posts' 和 'close_comments_days_old' 选项来控制是否启用和天数阈值。
- 使用 close_comments_for_post_types 过滤器允许开发者自定义自动关闭评论的文章类型列表,默认仅包括 'post'。
- 函数检查文章是否为单篇文章、文章类型是否匹配、文章是否超过指定天数,条件满足时将 comment_status 和 ping_status 设置为 'closed'。
代码示例
add_filter( 'close_comments_for_post_types', 'wpdocs_close_comments' );
function wpdocs_close_comments() : array {
return array( 'your_old_custom_post_type' );
}注意事项
- 此函数仅影响查询返回的文章对象,不直接修改数据库,适用于性能优化场景。
- 开发者可以通过 close_comments_for_post_types 过滤器扩展支持自定义文章类型,确保兼容性。
原文内容
Closes comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
Parameters
Source
function _close_comments_for_old_posts( $posts, $query ) {
if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) ) {
return $posts;
}
/**
* Filters the list of post types to automatically close comments for.
*
* @since 3.2.0
*
* @param string[] $post_types An array of post type names.
*/
$post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
if ( ! in_array( $posts[0]->post_type, $post_types, true ) ) {
return $posts;
}
$days_old = (int) get_option( 'close_comments_days_old' );
if ( ! $days_old ) {
return $posts;
}
if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
$posts[0]->comment_status = 'closed';
$posts[0]->ping_status = 'closed';
}
return $posts;
}
Hooks
- apply_filters( ‘close_comments_for_post_types’, string[] $post_types )
-
Filters the list of post types to automatically close comments for.
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |
Skip to note 2 content
azadehnoory
Automatically disable comments on old custom post types:
add_filter( 'close_comments_for_post_types', 'wpdocs_close_comments' ); function wpdocs_close_comments() : array { return array( 'your_old_custom_post_type' ); }