render_block_core_comments

函数
render_block_core_comments ( $attributes, $content, $block )
参数
  • (array) $attributes Block attributes.
    Required:
  • (string) $content Block default content.
    Required:
  • (WP_Block) $block Block instance.
    Required:
返回值
  • (string) Returns the filtered post comments for the current post wrapped inside "p" tags.
定义位置
相关方法
render_block_core_comments_titleregister_block_core_commentsrender_block_core_comment_daterender_block_core_latest_commentsrender_block_core_cover
引入
-
弃用
-

render_block_core_comments: 这个函数用来渲染WordPress中的评论块。评论块显示一个文章或页面上的评论列表: 这个函数负责生成评论块的HTML标记。

在服务器上渲染`core/comments’区块。

这个渲染回调主要是为了渲染这个区块的动态、传统的版本(旧的`core/post-comments`)。它使用`comments_template()`函数来生成输出,其方式与经典的PHP主题相同。

由于这个回调将在SSR期间一直运行,首先我们需要检查该块是否处于传统模式。如果不是,将返回编辑器中生成的HTML。

function render_block_core_comments( $attributes, $content, $block ) {
	global $post;

	$post_id = $block->context['postId'];
	if ( ! isset( $post_id ) ) {
		return '';
	}

	$comment_args = array(
		'post_id' => $post_id,
		'count'   => true,
		'status'  => 'approve',
	);
	// Return early if there are no comments and comments are closed.
	if ( ! comments_open( $post_id ) && get_comments( $comment_args ) === 0 ) {
		return '';
	}

	// If this isn't the legacy block, we need to render the static version of this block.
	$is_legacy = 'core/post-comments' === $block->name || ! empty( $attributes['legacy'] );
	if ( ! $is_legacy ) {
		return $block->render( array( 'dynamic' => false ) );
	}

	$post_before = $post;
	$post        = get_post( $post_id );
	setup_postdata( $post );

	ob_start();

	/*
	 * There's a deprecation warning generated by WP Core.
	 * Ideally this deprecation is removed from Core.
	 * In the meantime, this removes it from the output.
	 */
	add_filter( 'deprecated_file_trigger_error', '__return_false' );
	comments_template();
	remove_filter( 'deprecated_file_trigger_error', '__return_false' );

	$output = ob_get_clean();
	$post   = $post_before;

	$classnames = array();
	// Adds the old class name for styles' backwards compatibility.
	if ( isset( $attributes['legacy'] ) ) {
		$classnames[] = 'wp-block-post-comments';
	}
	if ( isset( $attributes['textAlign'] ) ) {
		$classnames[] = 'has-text-align-' . $attributes['textAlign'];
	}

	$wrapper_attributes = get_block_wrapper_attributes(
		array( 'class' => implode( ' ', $classnames ) )
	);

	/*
	 * Enqueues scripts and styles required only for the legacy version. That is
	 * why they are not defined in `block.json`.
	 */
	wp_enqueue_script( 'comment-reply' );
	enqueue_legacy_post_comments_block_styles( $block->name );

	return sprintf( '<div %1$s>%2$s</div>', $wrapper_attributes, $output );
}

常见问题

FAQs
查看更多 >