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