| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/comment-template` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/comment-template` block on the server. |
| 10 |
* |
| 11 |
* @param array $attributes Block attributes. |
| 12 |
* @param string $content Block default content. |
| 13 |
* @param WP_Block $block Block instance. |
| 14 |
* |
| 15 |
* @return string Returns the HTML representing the comments using the layout |
| 16 |
* defined by the block's inner blocks. |
| 17 |
*/ |
| 18 |
function gutenberg_render_block_core_comment_template( $attributes, $content, $block ) { |
| 19 |
|
| 20 |
$post_id = $block->context['postId']; |
| 21 |
|
| 22 |
// Bail out early if the post ID is not set for some reason. |
| 23 |
if ( ! isset( $post_id ) ) { |
| 24 |
return ''; |
| 25 |
} |
| 26 |
|
| 27 |
$number = $block->context['queryPerPage']; |
| 28 |
|
| 29 |
// Get an array of comments for the current post. |
| 30 |
$comments = get_approved_comments( $post_id, array( 'number' => $number ) ); |
| 31 |
|
| 32 |
if ( count( $comments ) === 0 ) { |
| 33 |
return ''; |
| 34 |
} |
| 35 |
|
| 36 |
$content = ''; |
| 37 |
foreach ( $comments as $comment ) { |
| 38 |
$block_content = ( new WP_Block( |
| 39 |
$block->parsed_block, |
| 40 |
array( |
| 41 |
'commentId' => $comment->comment_ID, |
| 42 |
) |
| 43 |
) )->render( array( 'dynamic' => false ) ); |
| 44 |
$content .= '<li>' . $block_content . '</li>'; |
| 45 |
} |
| 46 |
|
| 47 |
return sprintf( |
| 48 |
'<ul>%1$s</ul>', |
| 49 |
$content |
| 50 |
); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Registers the `core/comment-template` block on the server. |
| 55 |
*/ |
| 56 |
function gutenberg_register_block_core_comment_template() { |
| 57 |
register_block_type_from_metadata( |
| 58 |
__DIR__ . '/comment-template', |
| 59 |
array( |
| 60 |
'render_callback' => 'gutenberg_render_block_core_comment_template', |
| 61 |
'skip_inner_blocks' => true, |
| 62 |
) |
| 63 |
); |
| 64 |
} |
| 65 |
add_action( 'init', 'gutenberg_register_block_core_comment_template', 20 ); |
| 66 |
|