函数文档

_close_comments_for_old_post()

💡 云策文档标注

概述

_close_comments_for_old_post() 是一个 WordPress 函数,用于根据文章发布时间自动关闭评论。它通过 comments_open 和 pings_open 钩子调用,检查文章是否超过指定天数,以决定评论是否开放。

关键要点

  • 函数用于关闭旧文章的评论,基于 close_comments_for_old_posts 和 close_comments_days_old 选项设置。
  • 通过 close_comments_for_post_types 过滤器可以自定义自动关闭评论的文章类型。
  • 函数返回布尔值 $open,表示评论是否开放,若文章超过指定天数则返回 false。

代码示例

function _close_comments_for_old_post( $open, $post_id ) {
	if ( ! $open ) {
		return $open;
	}

	if ( ! get_option( 'close_comments_for_old_posts' ) ) {
		return $open;
	}

	$days_old = (int) get_option( 'close_comments_days_old' );
	if ( ! $days_old ) {
		return $open;
	}

	$post = get_post( $post_id );

	/** This filter is documented in wp-includes/comment.php */
	$post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
	if ( ! in_array( $post->post_type, $post_types, true ) ) {
		return $open;
	}

	// Undated drafts should not show up as comments closed.
	if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
		return $open;
	}

	if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
		return false;
	}

	return $open;
}

注意事项

  • 函数仅对 post 类型文章默认生效,可通过 close_comments_for_post_types 过滤器扩展。
  • 未设置日期的草稿文章不会被视为评论关闭。
  • 需要确保 close_comments_for_old_posts 和 close_comments_days_old 选项已正确配置。

📄 原文内容

Closes comments on an old post. Hooked to comments_open and pings_open.

Parameters

$openboolrequired
Comments open or closed.
$post_idintrequired
Post ID.

Return

bool $open

Source

function _close_comments_for_old_post( $open, $post_id ) {
	if ( ! $open ) {
		return $open;
	}

	if ( ! get_option( 'close_comments_for_old_posts' ) ) {
		return $open;
	}

	$days_old = (int) get_option( 'close_comments_days_old' );
	if ( ! $days_old ) {
		return $open;
	}

	$post = get_post( $post_id );

	/** This filter is documented in wp-includes/comment.php */
	$post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
	if ( ! in_array( $post->post_type, $post_types, true ) ) {
		return $open;
	}

	// Undated drafts should not show up as comments closed.
	if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
		return $open;
	}

	if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
		return false;
	}

	return $open;
}

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.