', esc_attr( $summary_type ) ); $html .= sprintf( '

%s %s

', esc_html__( 'Quick answer:', 'ai-answer-toolkit' ), esc_html( $summary ) ); $html .= ''; // Allow filtering of summary HTML return apply_filters( 'ai_answer_toolkit_summary_html', $html, $summary, $summary_type ); } /** * Inject summary into content. * * Injects after first H1 if found, otherwise at the top of content. * * @param string $content Original content. * @param string $summary_html Summary HTML to inject. * @return string Modified content. */ private static function inject_into_content( $content, $summary_html ) { // Try to find first H1 tag $h1_position = self::find_first_h1_position( $content ); if ( $h1_position !== false ) { // Inject after H1 return self::inject_after_h1( $content, $summary_html, $h1_position ); } // No H1 found, inject at top return $summary_html . "\n\n" . $content; } /** * Find position of first H1 closing tag. * * @param string $content Content to search. * @return int|false Position of H1 closing tag or false if not found. */ private static function find_first_h1_position( $content ) { // Match opening H1 tag (with or without attributes) $pattern = '/]*>.*?<\/h1>/is'; if ( preg_match( $pattern, $content, $matches, PREG_OFFSET_CAPTURE ) ) { // Return position after the closing tag $h1_match = $matches[0][0]; $h1_start = $matches[0][1]; $h1_end = $h1_start + strlen( $h1_match ); return $h1_end; } return false; } /** * Inject summary after H1 tag. * * @param string $content Original content. * @param string $summary_html Summary HTML. * @param int $position Position to inject at. * @return string Modified content. */ private static function inject_after_h1( $content, $summary_html, $position ) { $before = substr( $content, 0, $position ); $after = substr( $content, $position ); return $before . "\n\n" . $summary_html . "\n\n" . $after; } /** * Reset rendering flag. * * Useful for testing or when rendering multiple posts in a loop. */ public static function reset_rendering_flag() { self::$summary_rendered = false; } } AI_Answer_Toolkit_Frontend::init();