Last active
August 12, 2021 14:18
-
-
Save markhowellsmead/946fba77ec48acdb2ba14b41dd39b98f to your computer and use it in GitHub Desktop.
Example of how to customise the output of a core block (since WP 5.8). Planned for integration to a Hello Roots Theme.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace SayHello\Theme\Block; | |
/** | |
* Customisation of the Core Post Title block | |
* Find the original core rendering at e.g. wp-includes/blocks/post-title.php | |
* | |
* @author Mark Howells-Mead <mark@sayhello.ch> | |
*/ | |
class PostTitle | |
{ | |
public function run() | |
{ | |
remove_action('init', 'register_block_core_post_title'); | |
add_action('init', [$this, 'registerBlockCorePostTitle']); | |
} | |
/** | |
* Server-side rendering of the `core/post-title` block. | |
* | |
* @package WordPress | |
*/ | |
/** | |
* Renders the `core/post-title` block on the server. | |
* | |
* @param array $attributes Block attributes. | |
* @param string $content Block default content. | |
* @param WP_Block $block Block instance. | |
* | |
* @return string Returns the filtered post title for the current post wrapped inside "h1" tags. | |
*/ | |
public function renderBlockCorePostTitle($attributes, $content, $block) | |
{ | |
if (!isset($block->context['postId'])) { | |
return ''; | |
} | |
$post_ID = $block->context['postId']; | |
$tag_name = 'h2'; | |
$align_class_name = empty($attributes['textAlign']) ? '' : "has-text-align-{$attributes['textAlign']}"; | |
if (isset($attributes['level'])) { | |
$tag_name = 0 === $attributes['level'] ? 'p' : 'h' . $attributes['level']; | |
} | |
$title = get_the_title($post_ID); | |
if (isset($attributes['isLink']) && $attributes['isLink']) { | |
$title = sprintf('<a href="%1s" target="%2s" rel="%3s">%4s</a>', get_the_permalink($post_ID), $attributes['linkTarget'], $attributes['rel'], $title); | |
} | |
$wrapper_attributes = get_block_wrapper_attributes(array('class' => $align_class_name)); | |
return sprintf( | |
'<%1$s %2$s>%3$s</%1$s>', | |
$tag_name, | |
$wrapper_attributes, | |
$title | |
); | |
} | |
/** | |
* Registers the `core/post-title` block on the server. | |
*/ | |
public function registerBlockCorePostTitle() | |
{ | |
register_block_type_from_metadata( | |
ABSPATH . WPINC . '/blocks/post-title', | |
array( | |
'render_callback' => [$this, 'renderBlockCorePostTitle'], | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment