| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/template-part` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/template-part` block on the server. |
| 10 |
* |
| 11 |
* @param array $attributes The block attributes. |
| 12 |
* |
| 13 |
* @return string The render. |
| 14 |
*/ |
| 15 |
function gutenberg_render_block_core_template_part( $attributes ) { |
| 16 |
$content = null; |
| 17 |
|
| 18 |
if ( ! empty( $attributes['postId'] ) ) { |
| 19 |
// If we have a post ID, which means this template part |
| 20 |
// is user-customized, render the corresponding post content. |
| 21 |
$content = get_post( $attributes['postId'] )->post_content; |
| 22 |
} elseif ( wp_get_theme()->get( 'TextDomain' ) === $attributes['theme'] ) { |
| 23 |
// Else, if the template part was provided by the active theme, |
| 24 |
// render the corresponding file content. |
| 25 |
$template_part_file_path = |
| 26 |
get_stylesheet_directory() . '/block-template-parts/' . $attributes['slug'] . '.html'; |
| 27 |
if ( file_exists( $template_part_file_path ) ) { |
| 28 |
$content = file_get_contents( $template_part_file_path ); |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
if ( is_null( $content ) ) { |
| 33 |
return 'Template Part Not Found'; |
| 34 |
} |
| 35 |
return apply_filters( 'the_content', str_replace( ']]>', ']]>', $content ) ); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Registers the `core/template-part` block on the server. |
| 40 |
*/ |
| 41 |
function gutenberg_register_block_core_template_part() { |
| 42 |
register_block_type( |
| 43 |
'core/template-part', |
| 44 |
array( |
| 45 |
'attributes' => array( |
| 46 |
'postId' => array( |
| 47 |
'type' => 'number', |
| 48 |
), |
| 49 |
'slug' => array( |
| 50 |
'type' => 'string', |
| 51 |
), |
| 52 |
'theme' => array( |
| 53 |
'type' => 'string', |
| 54 |
), |
| 55 |
), |
| 56 |
'render_callback' => 'gutenberg_render_block_core_template_part', |
| 57 |
) |
| 58 |
); |
| 59 |
} |
| 60 |
add_action( 'init', 'gutenberg_register_block_core_template_part', 20 ); |
| 61 |
|