1<?php
2/**
3 * Server-side rendering of the `core/post-comments-link` block.
4 *
5 * @package WordPress
6 */
7
8/**
9 * Renders the `core/post-comments-link` block on the server.
10 *
11 * @since 6.9.0
12 *
13 * @param array $attributes Block attributes.
14 * @param string $content Block default content.
15 * @param WP_Block $block Block instance.
16 * @return string Returns the rendered link.
17 */
18function render_block_core_post_comments_link( $attributes, $content, $block ) {
19 if (
20 ! isset( $block->context['postId'] ) ||
21 isset( $block->context['postId'] ) &&
22 ! comments_open( $block->context['postId'] )
23 ) {
24 return '';
25 }
26
27 $classes = array();
28 if ( isset( $attributes['textAlign'] ) ) {
29 $classes[] = 'has-text-align-' . $attributes['textAlign'];
30 }
31 if ( isset( $attributes['style']['elements']['link']['color']['text'] ) ) {
32 $classes[] = 'has-link-color';
33 }
34 $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => implode( ' ', $classes ) ) );
35 $comments_number = (int) get_comments_number( $block->context['postId'] );
36 $comments_link = get_comments_link( $block->context['postId'] );
37 $post_title = get_the_title( $block->context['postId'] );
38 $comment_html = '';
39
40 if ( 0 === $comments_number ) {
41 $comment_html = sprintf(
42 /* translators: %s post title */
43 __( 'No comments<span class="screen-reader-text"> on %s</span>' ),
44 $post_title
45 );
46 } else {
47 $comment_html = sprintf(
48 /* translators: 1: Number of comments, 2: post title */
49 _n(
50 '%1$s comment<span class="screen-reader-text"> on %2$s</span>',
51 '%1$s comments<span class="screen-reader-text"> on %2$s</span>',
52 $comments_number
53 ),
54 esc_html( number_format_i18n( $comments_number ) ),
55 $post_title
56 );
57 }
58
59 return '<div ' . $wrapper_attributes . '><a href=' . esc_url( $comments_link ) . '>' . $comment_html . '</a></div>';
60}
61
62/**
63 * Registers the `core/post-comments-link` block on the server.
64 *
65 * @since 6.9.0
66 */
67function register_block_core_post_comments_link() {
68 register_block_type_from_metadata(
69 __DIR__ . '/post-comments-link',
70 array(
71 'render_callback' => 'render_block_core_post_comments_link',
72 )
73 );
74}
75add_action( 'init', 'register_block_core_post_comments_link' );
76