class-popup-button-render.php
53 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SuperbAddons\Gutenberg\Popup; |
| 4 | |
| 5 | defined('ABSPATH') || exit(); |
| 6 | |
| 7 | /** |
| 8 | * Filters the rendered output of core/button blocks that have a |
| 9 | * spbaddPopupTarget attribute, converting them into popup trigger buttons. |
| 10 | * |
| 11 | * The spbaddPopupTarget attribute is stored only in the block comment |
| 12 | * delimiter (not in the saved HTML), so deactivating this plugin causes |
| 13 | * no block validation errors — the button simply renders normally. |
| 14 | */ |
| 15 | class PopupButtonRender |
| 16 | { |
| 17 | public static function Initialize() |
| 18 | { |
| 19 | add_filter('render_block_core/button', array(__CLASS__, 'MaybeRenderPopupTrigger'), 10, 2); |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * If a core/button has the spbaddPopupTarget attribute, modify its |
| 24 | * rendered HTML to act as a popup trigger. |
| 25 | */ |
| 26 | public static function MaybeRenderPopupTrigger($block_content, $block) |
| 27 | { |
| 28 | if (empty($block['attrs']['spbaddPopupTarget'])) { |
| 29 | return $block_content; |
| 30 | } |
| 31 | |
| 32 | $popup_target = sanitize_text_field($block['attrs']['spbaddPopupTarget']); |
| 33 | if (empty($popup_target)) { |
| 34 | return $block_content; |
| 35 | } |
| 36 | |
| 37 | $processor = new \WP_HTML_Tag_Processor($block_content); |
| 38 | |
| 39 | // Find the inner <a> element (core/button renders as <div><a>...</a></div>) |
| 40 | if ($processor->next_tag('a')) { |
| 41 | $processor->set_attribute('data-popup-target', $popup_target); |
| 42 | $processor->set_attribute('aria-haspopup', 'dialog'); |
| 43 | $processor->set_attribute('role', 'button'); |
| 44 | // Remove link-specific attributes since this is now a button |
| 45 | $processor->remove_attribute('href'); |
| 46 | $processor->remove_attribute('target'); |
| 47 | $processor->remove_attribute('rel'); |
| 48 | } |
| 49 | |
| 50 | return $processor->get_updated_html(); |
| 51 | } |
| 52 | } |
| 53 |