supported_blocks as $block ) { add_filter( 'render_block_' . $block, array( $this, 'apply_performance_attrs' ), 20, 2 ); } } /** * Check if block is an image block * * @param string $name Block name. * @return bool */ private function is_supported( $name ) { return in_array( $name, $this->supported_blocks ); } /** * Declare custom attributes for image block * * @param array $settings Block settings. * @return array Modified settings. */ public function declare_attribute( $settings ) { if ( empty( $settings['name'] ) ) { return $settings; } if ( ! $this->is_supported( $settings['name'] ) ) { return $settings; } if ( ! empty( $settings['attributes'] ) ) { // Fetch priority: high | low | empty (auto/browser default) $settings['attributes']['fetchPriority'] = array( 'type' => 'string', 'default' => '', ); // Loading: lazy | eager | empty (WP default) $settings['attributes']['loading'] = array( 'type' => 'string', 'default' => '', ); } return $settings; } /** * Enqueue editor scripts */ public function enqueue_settings_scripts() { wp_enqueue_script( 'brandy/image-performance', BRANDY_TEMPLATE_URL . '/inc/BlockSettings/ImagePerformance/script.js', array( 'wp-edit-post', 'wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-compose', 'wp-hooks', 'wp-i18n' ), BRANDY_SCRIPT_VERSION, true ); } /** * Apply performance attributes to rendered image block * * @param string $html Block HTML. * @param array $block Block data. * @return string Modified HTML. */ public function apply_performance_attrs( $html, $block ) { $attrs = $block['attrs'] ?? array(); $fetch_priority = $attrs['fetchPriority'] ?? ''; $loading = $attrs['loading'] ?? ''; // Skip if no custom attrs set if ( empty( $fetch_priority ) && empty( $loading ) ) { return $html; } $tag = new \WP_HTML_Tag_Processor( $html ); if ( $tag->next_tag( 'img' ) ) { // Apply fetchpriority if set if ( ! empty( $fetch_priority ) ) { $tag->set_attribute( 'fetchpriority', $fetch_priority ); } // Apply loading if set (overrides WP default) if ( ! empty( $loading ) ) { $tag->set_attribute( 'loading', $loading ); } } return $tag->get_updated_html(); } } Caller::get_instance();