1<?php
2/**
3 * Server-side rendering of the `core/button` block.
4 *
5 * @package WordPress
6 */
7
8/**
9 * Renders the `core/button` block on the server,
10 *
11 * @since 6.6.0
12 *
13 * @param array $attributes The block attributes.
14 * @param string $content The block content.
15 *
16 * @return string The block content.
17 */
18function render_block_core_button( $attributes, $content ) {
19 $p = new WP_HTML_Tag_Processor( $content );
20
21 /*
22 * The button block can render an `<a>` or `<button>` and also has a
23 * `<div>` wrapper. Find the a or button tag.
24 */
25 $tag = null;
26 while ( $p->next_tag() ) {
27 $tag = $p->get_tag();
28 if ( 'A' === $tag || 'BUTTON' === $tag ) {
29 break;
30 }
31 }
32
33 /*
34 * If this happens, the likelihood is there's no block content,
35 * or the block has been modified by a plugin.
36 */
37 if ( null === $tag ) {
38 return $content;
39 }
40
41 // If the next token is the closing tag, the button is empty.
42 $is_empty = true;
43 while ( $p->next_token() && $tag !== $p->get_token_name() && $is_empty ) {
44 if ( '#comment' !== $p->get_token_type() ) {
45 /**
46 * Anything else implies this is not empty.
47 * This might include any text content (including a space),
48 * inline images or other HTML.
49 */
50 $is_empty = false;
51 }
52 }
53
54 /*
55 * When there's no text, render nothing for the block.
56 * See https://github.com/WordPress/gutenberg/issues/17221 for the
57 * reasoning behind this.
58 */
59 if ( $is_empty ) {
60 return '';
61 }
62
63 return $content;
64}
65
66/**
67 * Registers the `core/button` block on server.
68 *
69 * @since 6.6.0
70 */
71function register_block_core_button() {
72 register_block_type_from_metadata(
73 __DIR__ . '/button',
74 array(
75 'render_callback' => 'render_block_core_button',
76 )
77 );
78}
79add_action( 'init', 'register_block_core_button' );
80