| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/post-hierarchical-terms` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/post-hierarchical-terms` 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 |
* @return string Returns the filtered post hierarchical terms for the current post wrapped inside "a" tags. |
| 15 |
*/ |
| 16 |
function gutenberg_render_block_core_post_hierarchical_terms( $attributes, $content, $block ) { |
| 17 |
if ( ! isset( $block->context['postId'] ) || ! isset( $attributes['term'] ) ) { |
| 18 |
return ''; |
| 19 |
} |
| 20 |
|
| 21 |
$post_hierarchical_terms = get_the_terms( $block->context['postId'], $attributes['term'] ); |
| 22 |
if ( is_wp_error( $post_hierarchical_terms ) ) { |
| 23 |
return ''; |
| 24 |
} |
| 25 |
if ( empty( $post_hierarchical_terms ) ) { |
| 26 |
return ''; |
| 27 |
} |
| 28 |
|
| 29 |
$align_class_name = empty( $attributes['textAlign'] ) ? '' : ' ' . "has-text-align-{$attributes['textAlign']}"; |
| 30 |
|
| 31 |
$terms_links = ''; |
| 32 |
foreach ( $post_hierarchical_terms as $term ) { |
| 33 |
$terms_links .= sprintf( |
| 34 |
'<a href="%1$s">%2$s</a> | ', |
| 35 |
get_term_link( $term->term_id ), |
| 36 |
esc_html( $term->name ) |
| 37 |
); |
| 38 |
} |
| 39 |
$terms_links = trim( $terms_links, ' | ' ); |
| 40 |
$wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $align_class_name ) ); |
| 41 |
|
| 42 |
return sprintf( |
| 43 |
'<div %1$s>%2$s</div>', |
| 44 |
$wrapper_attributes, |
| 45 |
$terms_links |
| 46 |
); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Registers the `core/post-hierarchical-terms` block on the server. |
| 51 |
*/ |
| 52 |
function gutenberg_register_block_core_post_hierarchical_terms() { |
| 53 |
register_block_type_from_metadata( |
| 54 |
__DIR__ . '/post-hierarchical-terms', |
| 55 |
array( |
| 56 |
'render_callback' => 'gutenberg_render_block_core_post_hierarchical_terms', |
| 57 |
) |
| 58 |
); |
| 59 |
} |
| 60 |
add_action( 'init', 'gutenberg_register_block_core_post_hierarchical_terms', 20 ); |
| 61 |
|