1<?php
2/**
3 * Server-side rendering of the `core/post-title` block.
4 *
5 * @package WordPress
6 */
7
8/**
9 * Renders the `core/post-title` block on the server.
10 *
11 * @since 6.3.0 Omitting the $post argument from the `get_the_title`.
12 *
13 * @param array $attributes Block attributes.
14 * @param string $content Block default content.
15 * @param WP_Block $block Block instance.
16 *
17 * @return string Returns the filtered post title for the current post wrapped inside "h1" tags.
18 */
19function render_block_core_post_title( $attributes, $content, $block ) {
20 if ( ! isset( $block->context['postId'] ) ) {
21 return '';
22 }
23
24 /**
25 * The `$post` argument is intentionally omitted so that changes are reflected when previewing a post.
26 * See: https://github.com/WordPress/gutenberg/pull/37622#issuecomment-1000932816.
27 */
28 $title = get_the_title();
29
30 if ( ! $title ) {
31 return '';
32 }
33
34 $tag_name = 'h2';
35 if ( isset( $attributes['level'] ) ) {
36 $tag_name = 0 === $attributes['level'] ? 'p' : 'h' . (int) $attributes['level'];
37 }
38
39 if ( isset( $attributes['isLink'] ) && $attributes['isLink'] ) {
40 $rel = ! empty( $attributes['rel'] ) ? 'rel="' . esc_attr( $attributes['rel'] ) . '"' : '';
41 $title = sprintf( '<a href="%1$s" target="%2$s" %3$s>%4$s</a>', esc_url( get_the_permalink( $block->context['postId'] ) ), esc_attr( $attributes['linkTarget'] ), $rel, $title );
42 }
43
44 $classes = array();
45 if ( isset( $attributes['textAlign'] ) ) {
46 $classes[] = 'has-text-align-' . $attributes['textAlign'];
47 }
48 if ( isset( $attributes['style']['elements']['link']['color']['text'] ) ) {
49 $classes[] = 'has-link-color';
50 }
51 $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => implode( ' ', $classes ) ) );
52
53 return sprintf(
54 '<%1$s %2$s>%3$s</%1$s>',
55 $tag_name,
56 $wrapper_attributes,
57 $title
58 );
59}
60
61/**
62 * Registers the `core/post-title` block on the server.
63 *
64 * @since 5.8.0
65 */
66function register_block_core_post_title() {
67 register_block_type_from_metadata(
68 __DIR__ . '/post-title',
69 array(
70 'render_callback' => 'render_block_core_post_title',
71 )
72 );
73}
74add_action( 'init', 'register_block_core_post_title' );
75