wpseek.com
A WordPress-centric search engine for devs and theme authors



render_block_core_comments › WordPress Function

Since6.1.0
Deprecatedn/a
render_block_core_comments ( $attributes, $content, $block )
Parameters: (3)
  • (array) $attributes Block attributes.
    Required: Yes
  • (string) $content Block default content.
    Required: Yes
  • (WP_Block) $block Block instance.
    Required: Yes
Returns:
  • (string) Returns the filtered post comments for the current post wrapped inside "p" tags.
Defined at:
Codex:

Renders the `core/comments` block on the server.

This render callback is mainly for rendering a dynamic, legacy version of this block (the old core/post-comments). It uses the comments_template() function to generate the output, in the same way as classic PHP themes. As this callback will always run during SSR, first we need to check whether the block is in legacy mode. If not, the HTML generated in the editor is returned instead.


Source

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

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

	// Return early if there are no comments and comments are closed.
	if ( ! comments_open( $post_id ) && (int) get_comments_number( $post_id ) === 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 );
}