Last active
March 26, 2026 12:05
-
-
Save roborourke/5426460f0a0228ddb6c7a52a5e6282ed to your computer and use it in GitHub Desktop.
WordPress Post Template Link Cover
This file contains hidden or 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 | |
| /** | |
| * Block Style For covering post template blocks with clickable link. | |
| */ | |
| add_action( 'init', function () { | |
| register_block_style( | |
| 'core/post-title', | |
| [ | |
| 'name' => 'link-cover', | |
| 'label' => 'Link Cover', | |
| 'inline_style' => <<<CSS | |
| .wp-block-post:has(.is-style-link-cover) { | |
| position: relative; | |
| anchor-name: var(--anchor-name, --post); | |
| } | |
| .wp-block-post:has(.is-style-link-cover) a[href] { | |
| position: relative; | |
| z-index: 2; | |
| } | |
| .wp-block-post .is-style-link-cover > a[href] { | |
| position: static; | |
| } | |
| .wp-block-post-title.is-style-link-cover > a[href]::after { | |
| content: ""; | |
| position: fixed; | |
| position-anchor: var(--anchor-name, --post); | |
| z-index: 1; | |
| margin: 0; | |
| left: anchor( left ); | |
| top: anchor( top ); | |
| right: anchor( right ); | |
| bottom: anchor( bottom ); | |
| } | |
| CSS, | |
| ] | |
| ); | |
| } ); | |
| /** | |
| * Inject CSS anchor names into post blocks. | |
| * | |
| * @param string $block_content The block HTML. | |
| * @return string | |
| */ | |
| add_filter( 'render_block_core/post-template', function ( string $block_content ) : string { | |
| static $template_instance = 1; | |
| $block_content = new WP_HTML_Tag_Processor( $block_content ); | |
| while ( $block_content->next_tag( [ 'class_name' => 'wp-block-post' ] ) ) { | |
| $var_name = preg_replace( '/^.*?\s(post-\d+)\s.*?$/', '$1', $block_content->get_attribute( 'class' ) ); | |
| $style = $block_content->get_attribute( 'style' ); | |
| $block_content->set_attribute( 'style', $style . ';--anchor-name:--' . $var_name . '--' . $template_instance ); | |
| } | |
| $template_instance++; | |
| return (string) $block_content; | |
| }, 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment