post_parent ) { return []; } $post_id = (int) $attachment->post_parent; $alts = []; // 1. Featured image alt. $featured_id = get_post_thumbnail_id( $post_id ); if ( $featured_id && $featured_id !== $attachment_id ) { $featured_alt = get_post_meta( $featured_id, '_wp_attachment_image_alt', true ); if ( $featured_alt ) { $alts[] = $featured_alt; } } // 2. Alts from images in the content. $content = get_post_field( 'post_content', $post_id ); if ( $content && preg_match_all( '/]+>/i', $content, $matches ) ) { foreach ( $matches[0] as $img_tag ) { $img_id = 0; $alt = ''; // Try to get attachment ID from class="... wp-image-123 ..." if ( preg_match( '/wp-image-([0-9]+)/', $img_tag, $m ) ) { $img_id = (int) $m[1]; } // Skip the current attachment. if ( $img_id && $img_id === (int) $attachment_id ) { continue; } if ( $img_id ) { $alt = get_post_meta( $img_id, '_wp_attachment_image_alt', true ); } // Fallback: alt attribute in the HTML tag. if ( ! $alt && preg_match( '/alt=["\']([^"\']+)["\']/', $img_tag, $m_alt ) ) { $alt = wp_strip_all_tags( $m_alt[1] ); } if ( $alt ) { $alts[] = $alt; } } } // Normalize: trim, remove empties, dedupe. $alts = array_values( array_unique( array_filter( array_map( 'trim', $alts ) ) ) ); // Limit how many to include in the prompt (keep token usage sane). $max = 10; if ( count( $alts ) > $max ) { $alts = array_slice( $alts, 0, $max ); } return $alts; } public static function trim_to_words( $string, $max_words ) { // Split the string into words $words = preg_split( '/\s+/', trim( $string ) ); // If word count is within the limit, return original if ( count( $words ) <= $max_words ) { return $string; } // Take only the first $max_words and join them $trimmed = implode( ' ', array_slice( $words, 0, $max_words ) ); // Add ellipsis or other indicator if you like return $trimmed . '...'; } }