| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/footnotes` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/footnotes` 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 footnotes. |
| 16 |
*/ |
| 17 |
function gutenberg_render_block_core_footnotes( $attributes, $content, $block ) { |
| 18 |
// Bail out early if the post ID is not set for some reason. |
| 19 |
if ( empty( $block->context['postId'] ) ) { |
| 20 |
return ''; |
| 21 |
} |
| 22 |
|
| 23 |
if ( post_password_required( $block->context['postId'] ) ) { |
| 24 |
return; |
| 25 |
} |
| 26 |
|
| 27 |
$footnotes = get_post_meta( $block->context['postId'], 'footnotes', true ); |
| 28 |
|
| 29 |
if ( ! $footnotes ) { |
| 30 |
return; |
| 31 |
} |
| 32 |
|
| 33 |
$footnotes = json_decode( $footnotes, true ); |
| 34 |
|
| 35 |
if ( count( $footnotes ) === 0 ) { |
| 36 |
return ''; |
| 37 |
} |
| 38 |
|
| 39 |
$wrapper_attributes = get_block_wrapper_attributes(); |
| 40 |
|
| 41 |
$block_content = ''; |
| 42 |
|
| 43 |
foreach ( $footnotes as $footnote ) { |
| 44 |
$block_content .= sprintf( |
| 45 |
'<li id="%1$s">%2$s <a href="#%1$s-link">↩︎</a></li>', |
| 46 |
$footnote['id'], |
| 47 |
$footnote['content'] |
| 48 |
); |
| 49 |
} |
| 50 |
|
| 51 |
return sprintf( |
| 52 |
'<ol %1$s>%2$s</ol>', |
| 53 |
$wrapper_attributes, |
| 54 |
$block_content |
| 55 |
); |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Registers the `core/footnotes` block on the server. |
| 60 |
*/ |
| 61 |
function gutenberg_register_block_core_footnotes() { |
| 62 |
foreach ( array( 'post', 'page' ) as $post_type ) { |
| 63 |
register_post_meta( |
| 64 |
$post_type, |
| 65 |
'footnotes', |
| 66 |
array( |
| 67 |
'show_in_rest' => true, |
| 68 |
'single' => true, |
| 69 |
'type' => 'string', |
| 70 |
) |
| 71 |
); |
| 72 |
} |
| 73 |
register_block_type_from_metadata( |
| 74 |
__DIR__ . '/footnotes', |
| 75 |
array( |
| 76 |
'render_callback' => 'gutenberg_render_block_core_footnotes', |
| 77 |
) |
| 78 |
); |
| 79 |
} |
| 80 |
add_action( 'init', 'gutenberg_register_block_core_footnotes', 20 ); |
| 81 |
|