extract_basic_fields( $post_id, $schema_type, $ai_entities ) ); $data = array_merge( $data, $this->extract_contact_fields( $post_id, $schema_type, $ai_entities ) ); $data = array_merge( $data, $this->extract_location_fields( $post_id, $schema_type, $ai_entities ) ); $data = array_merge( $data, $this->extract_rating_fields( $post_id, $schema_type, $ai_entities ) ); $data = array_merge( $data, $this->extract_price_fields( $post_id, $schema_type, $ai_entities ) ); $data = array_merge( $data, $this->extract_date_fields( $post_id, $schema_type, $ai_entities ) ); $data = array_merge( $data, $this->extract_media_fields( $post_id, $schema_type, $ai_entities ) ); $data = array_merge( $data, $this->extract_person_fields( $post_id, $schema_type, $ai_entities ) ); return $this->clean_and_validate( $data, $schema_type ); } /** * Extract basic post fields: name/headline, description, URL. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Basic field data. */ public function extract_basic_fields( $post_id, $schema_type, $ai_entities = array() ) { $post = get_post( $post_id ); if ( ! $post ) { return array(); } $data = array(); // Title: use headline for Article-type schemas, name for everything else. $article_types = array( 'Article', 'BlogPosting', 'NewsArticle' ); if ( in_array( $schema_type, $article_types, true ) ) { $data['headline'] = ! empty( $ai_entities['headline'] ) ? sanitize_text_field( $ai_entities['headline'] ) : $post->post_title; } else { $data['name'] = ! empty( $ai_entities['name'] ) ? sanitize_text_field( $ai_entities['name'] ) : $post->post_title; } // Description. $data['description'] = ! empty( $ai_entities['description'] ) ? sanitize_text_field( $ai_entities['description'] ) : wp_trim_words( wp_strip_all_tags( $post->post_content ), 55 ); // URL. $data['url'] = get_permalink( $post_id ); return $data; } /** * Extract contact fields: telephone, email, address. * * Prefers AI entities; falls back to regex extraction from content. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Contact field data. */ public function extract_contact_fields( $post_id, $schema_type, $ai_entities = array() ) { $data = array(); $content = get_post_field( 'post_content', $post_id ); if ( empty( $content ) ) { $content = ''; } $content = wp_strip_all_tags( $content ); // Telephone. if ( ! empty( $ai_entities['telephone'] ) ) { $data['telephone'] = $this->format_phone( $ai_entities['telephone'] ); } elseif ( ! empty( $ai_entities['phone'] ) ) { $data['telephone'] = $this->format_phone( $ai_entities['phone'] ); } else { $phone = $this->find_phone_number( $content ); if ( $phone ) { $data['telephone'] = $this->format_phone( $phone ); } } // Email. if ( ! empty( $ai_entities['email'] ) ) { $data['email'] = sanitize_email( $ai_entities['email'] ); } else { $email = $this->find_email( $content ); if ( $email ) { $data['email'] = sanitize_email( $email ); } } // Address. if ( ! empty( $ai_entities['address'] ) ) { if ( is_array( $ai_entities['address'] ) ) { $data['address'] = $this->format_address( $ai_entities['address'] ); } else { $data['address'] = $this->format_address( array( 'streetAddress' => $ai_entities['address'] ) ); } } else { $address = $this->find_address( $content ); if ( $address ) { $data['address'] = $this->format_address( $address ); } } return $data; } /** * Find a phone number in content. * * Supports US, UK, and international phone number formats. * * @param string $content Plain-text content. * @return string|null Phone number string or null. */ public function find_phone_number( $content ) { $patterns = array( // US: (555) 123-4567, 555-123-4567, 555.123.4567, +1 555 123 4567 '/(?:\+?1[\s.-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}/', // UK: +44 20 7946 0958, 020 7946 0958, 07911 123456 '/(?:\+?44[\s.-]?)?\(?0?\d{2,4}\)?[\s.-]?\d{3,4}[\s.-]?\d{3,4}/', // International: +XX XXXX XXXXXX '/\+\d{1,3}[\s.-]?\d{1,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{0,4}/', ); foreach ( $patterns as $pattern ) { if ( preg_match( $pattern, $content, $matches ) ) { $number = trim( $matches[0] ); // Sanity check: must have at least 7 digits. $digits = preg_replace( '/[^\d]/', '', $number ); if ( strlen( $digits ) >= 7 ) { return $number; } } } return null; } /** * Find an email address in content. * * @param string $content Plain-text content. * @return string|null Email address or null. */ public function find_email( $content ) { $pattern = '/[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/'; if ( preg_match( $pattern, $content, $matches ) ) { return $matches[0]; } return null; } /** * Find a street address in content. * * Looks for common address patterns such as numbered streets, suites, * and city/state/zip combinations. * * @param string $content Plain-text content. * @return array|null PostalAddress components or null. */ public function find_address( $content ) { // Pattern for US-style street address: 123 Main Street, City, ST 12345 $pattern = '/(\d{1,5}\s+(?:[A-Z][a-zA-Z]*\s*){1,4}(?:Street|St|Avenue|Ave|Boulevard|Blvd|Drive|Dr|Road|Rd|Lane|Ln|Way|Court|Ct|Place|Pl|Circle|Cir)\.?)(?:\s*,?\s*(?:Suite|Ste|Apt|Unit|#)\s*\d+[A-Za-z]?)?\s*,?\s*([A-Z][a-zA-Z\s]+)\s*,?\s*([A-Z]{2})\s*(\d{5}(?:-\d{4})?)?/'; if ( preg_match( $pattern, $content, $matches ) ) { $address = array( 'streetAddress' => trim( $matches[1] ), ); if ( ! empty( $matches[2] ) ) { $address['addressLocality'] = trim( $matches[2] ); } if ( ! empty( $matches[3] ) ) { $address['addressRegion'] = trim( $matches[3] ); } if ( ! empty( $matches[4] ) ) { $address['postalCode'] = trim( $matches[4] ); } $address['addressCountry'] = 'US'; return $address; } return null; } /** * Format a raw phone number for consistent output. * * @param string $phone Raw phone number. * @return string Cleaned phone number. */ public function format_phone( $phone ) { // Remove excess whitespace. $phone = preg_replace( '/\s+/', ' ', trim( $phone ) ); return sanitize_text_field( $phone ); } /** * Format an address array into a schema.org PostalAddress structure. * * @param array $address Address components. * @return array Schema.org PostalAddress object. */ public function format_address( $address ) { $formatted = array( '@type' => 'PostalAddress', ); $fields = array( 'streetAddress', 'addressLocality', 'addressRegion', 'postalCode', 'addressCountry', ); foreach ( $fields as $field ) { if ( ! empty( $address[ $field ] ) ) { $formatted[ $field ] = sanitize_text_field( $address[ $field ] ); } } return $formatted; } /** * Extract location fields: geo coordinates, place name. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Location field data. */ public function extract_location_fields( $post_id, $schema_type, $ai_entities = array() ) { $data = array(); // Only relevant for Event, LocalBusiness, Place types. $location_types = array( 'Event', 'LocalBusiness', 'Place', 'Organization' ); if ( ! in_array( $schema_type, $location_types, true ) ) { return $data; } // Geo coordinates from AI entities. if ( ! empty( $ai_entities['latitude'] ) && ! empty( $ai_entities['longitude'] ) ) { $data['geo'] = array( '@type' => 'GeoCoordinates', 'latitude' => floatval( $ai_entities['latitude'] ), 'longitude' => floatval( $ai_entities['longitude'] ), ); } elseif ( ! empty( $ai_entities['geo'] ) && is_array( $ai_entities['geo'] ) ) { $data['geo'] = array_merge( array( '@type' => 'GeoCoordinates' ), $ai_entities['geo'] ); } // Check for geo meta fields from popular map plugins. $lat = get_post_meta( $post_id, '_latitude', true ); $lng = get_post_meta( $post_id, '_longitude', true ); if ( empty( $lat ) ) { $lat = get_post_meta( $post_id, 'geo_latitude', true ); } if ( empty( $lng ) ) { $lng = get_post_meta( $post_id, 'geo_longitude', true ); } if ( ! empty( $lat ) && ! empty( $lng ) && empty( $data['geo'] ) ) { $data['geo'] = array( '@type' => 'GeoCoordinates', 'latitude' => floatval( $lat ), 'longitude' => floatval( $lng ), ); } // Place name for events. if ( 'Event' === $schema_type ) { if ( ! empty( $ai_entities['location_name'] ) || ! empty( $ai_entities['venue'] ) ) { $place_name = ! empty( $ai_entities['venue'] ) ? $ai_entities['venue'] : $ai_entities['location_name']; $data['location'] = array( '@type' => 'Place', 'name' => sanitize_text_field( $place_name ), ); // Attach address to the location if we have one. if ( ! empty( $ai_entities['address'] ) ) { if ( is_array( $ai_entities['address'] ) ) { $data['location']['address'] = $this->format_address( $ai_entities['address'] ); } else { $data['location']['address'] = sanitize_text_field( $ai_entities['address'] ); } } } } return $data; } /** * Extract rating fields from WooCommerce or WordPress comments. * * Builds an AggregateRating object from available rating data. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Rating field data. */ public function extract_rating_fields( $post_id, $schema_type, $ai_entities = array() ) { $data = array(); // Only relevant for Product, Recipe, LocalBusiness, Review, Course, Service. $rated_types = array( 'Product', 'Recipe', 'LocalBusiness', 'Review', 'Course', 'Service' ); if ( ! in_array( $schema_type, $rated_types, true ) ) { return $data; } // AI entities first. if ( ! empty( $ai_entities['aggregateRating'] ) && is_array( $ai_entities['aggregateRating'] ) ) { $data['aggregateRating'] = array_merge( array( '@type' => 'AggregateRating' ), $ai_entities['aggregateRating'] ); return $data; } // WooCommerce product ratings. if ( 'Product' === $schema_type && function_exists( 'wc_get_product' ) ) { $product = wc_get_product( $post_id ); if ( $product && method_exists( $product, 'get_average_rating' ) ) { $avg_rating = $product->get_average_rating(); $review_count = $product->get_review_count(); if ( $avg_rating > 0 && $review_count > 0 ) { $data['aggregateRating'] = array( '@type' => 'AggregateRating', 'ratingValue' => floatval( $avg_rating ), 'reviewCount' => intval( $review_count ), 'bestRating' => 5, 'worstRating' => 1, ); return $data; } } } // WordPress comment-based ratings (meta key: rating). $comments = get_comments( array( 'post_id' => $post_id, 'status' => 'approve', 'type' => 'comment', 'number' => 1000, ) ); if ( ! empty( $comments ) ) { $ratings = array(); foreach ( $comments as $comment ) { $rating = get_comment_meta( $comment->comment_ID, 'rating', true ); if ( $rating && is_numeric( $rating ) ) { $ratings[] = floatval( $rating ); } } if ( ! empty( $ratings ) ) { $data['aggregateRating'] = array( '@type' => 'AggregateRating', 'ratingValue' => round( array_sum( $ratings ) / count( $ratings ), 1 ), 'reviewCount' => count( $ratings ), 'bestRating' => 5, 'worstRating' => 1, ); } } return $data; } /** * Extract price fields from WooCommerce products or AI entities. * * Builds an Offer or priceRange depending on the schema type. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Price field data. */ public function extract_price_fields( $post_id, $schema_type, $ai_entities = array() ) { $data = array(); // Offer for Product schema. if ( 'Product' === $schema_type ) { // WooCommerce product. if ( function_exists( 'wc_get_product' ) ) { $product = wc_get_product( $post_id ); if ( $product ) { $offer = array( '@type' => 'Offer', 'url' => get_permalink( $post_id ), 'availability' => $product->is_in_stock() ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock', 'priceCurrency' => get_woocommerce_currency(), ); if ( $product->is_type( 'variable' ) ) { $min_price = $product->get_variation_price( 'min' ); $max_price = $product->get_variation_price( 'max' ); $offer['price'] = $min_price; $offer['priceValidUntil'] = gmdate( 'Y-12-31' ); if ( $min_price !== $max_price ) { $data['offers'] = array( '@type' => 'AggregateOffer', 'lowPrice' => $min_price, 'highPrice' => $max_price, 'priceCurrency' => get_woocommerce_currency(), 'offerCount' => count( $product->get_available_variations() ), ); return $data; } } else { $offer['price'] = $product->get_price(); $sale_end = $product->get_date_on_sale_to(); if ( $sale_end ) { $offer['priceValidUntil'] = $sale_end->date( 'Y-m-d' ); } else { $offer['priceValidUntil'] = gmdate( 'Y-12-31' ); } } $data['offers'] = $offer; return $data; } } // AI detected price. if ( ! empty( $ai_entities['price'] ) ) { $data['offers'] = array( '@type' => 'Offer', 'price' => $ai_entities['price'], 'priceCurrency' => ! empty( $ai_entities['currency'] ) ? $ai_entities['currency'] : 'USD', 'url' => get_permalink( $post_id ), ); return $data; } } // Price range for LocalBusiness, Service, Restaurant. $price_range_types = array( 'LocalBusiness', 'Service', 'Restaurant' ); if ( in_array( $schema_type, $price_range_types, true ) ) { if ( ! empty( $ai_entities['priceRange'] ) ) { $data['priceRange'] = sanitize_text_field( $ai_entities['priceRange'] ); } elseif ( ! empty( $ai_entities['prices'] ) && is_array( $ai_entities['prices'] ) ) { $data['priceRange'] = $this->format_price_range( $ai_entities['prices'] ); } } // Offers for Event, Course. $offer_types = array( 'Event', 'Course' ); if ( in_array( $schema_type, $offer_types, true ) && ! empty( $ai_entities['price'] ) ) { $data['offers'] = array( '@type' => 'Offer', 'price' => $ai_entities['price'], 'priceCurrency' => ! empty( $ai_entities['currency'] ) ? $ai_entities['currency'] : 'USD', 'url' => get_permalink( $post_id ), ); if ( ! empty( $ai_entities['availability'] ) ) { $data['offers']['availability'] = $ai_entities['availability']; } } return $data; } /** * Extract date fields relevant to the schema type. * * Handles event start/end dates, publish/modified dates, and recipe times. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Date field data. */ public function extract_date_fields( $post_id, $schema_type, $ai_entities = array() ) { $data = array(); // Publish and modified dates for Article types. $article_types = array( 'Article', 'BlogPosting', 'NewsArticle', 'WebPage' ); if ( in_array( $schema_type, $article_types, true ) ) { $data['datePublished'] = get_the_date( 'c', $post_id ); $data['dateModified'] = get_the_modified_date( 'c', $post_id ); } // Event dates. if ( 'Event' === $schema_type ) { if ( ! empty( $ai_entities['startDate'] ) ) { $data['startDate'] = sanitize_text_field( $ai_entities['startDate'] ); } if ( ! empty( $ai_entities['endDate'] ) ) { $data['endDate'] = sanitize_text_field( $ai_entities['endDate'] ); } // Check for The Events Calendar meta. $event_start = get_post_meta( $post_id, '_EventStartDate', true ); $event_end = get_post_meta( $post_id, '_EventEndDate', true ); if ( ! empty( $event_start ) && empty( $data['startDate'] ) ) { $data['startDate'] = gmdate( 'c', strtotime( $event_start ) ); } if ( ! empty( $event_end ) && empty( $data['endDate'] ) ) { $data['endDate'] = gmdate( 'c', strtotime( $event_end ) ); } } // Recipe times. if ( 'Recipe' === $schema_type ) { if ( ! empty( $ai_entities['prepTime'] ) ) { $data['prepTime'] = sanitize_text_field( $ai_entities['prepTime'] ); } if ( ! empty( $ai_entities['cookTime'] ) ) { $data['cookTime'] = sanitize_text_field( $ai_entities['cookTime'] ); } if ( ! empty( $ai_entities['totalTime'] ) ) { $data['totalTime'] = sanitize_text_field( $ai_entities['totalTime'] ); } } return $data; } /** * Extract media fields: featured image as ImageObject. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Media field data. */ public function extract_media_fields( $post_id, $schema_type, $ai_entities = array() ) { $data = array(); // AI-provided image. if ( ! empty( $ai_entities['image'] ) ) { if ( is_array( $ai_entities['image'] ) ) { $data['image'] = array_merge( array( '@type' => 'ImageObject' ), $ai_entities['image'] ); } else { $data['image'] = array( '@type' => 'ImageObject', 'url' => esc_url( $ai_entities['image'] ), ); } return $data; } // Featured image. $thumbnail_id = get_post_thumbnail_id( $post_id ); if ( $thumbnail_id ) { $src = wp_get_attachment_image_src( $thumbnail_id, 'full' ); if ( $src ) { $alt = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true ); $data['image'] = array( '@type' => 'ImageObject', 'url' => $src[0], 'width' => $src[1], 'height' => $src[2], ); if ( ! empty( $alt ) ) { $data['image']['caption'] = sanitize_text_field( $alt ); } } } // WooCommerce product gallery images. if ( 'Product' === $schema_type && function_exists( 'wc_get_product' ) ) { $product = wc_get_product( $post_id ); if ( $product ) { $gallery_ids = $product->get_gallery_image_ids(); if ( ! empty( $gallery_ids ) && ! empty( $data['image'] ) ) { $images = array( $data['image'] ); foreach ( array_slice( $gallery_ids, 0, 5 ) as $image_id ) { $img_src = wp_get_attachment_image_src( $image_id, 'full' ); if ( $img_src ) { $images[] = array( '@type' => 'ImageObject', 'url' => $img_src[0], 'width' => $img_src[1], 'height' => $img_src[2], ); } } $data['image'] = $images; } } } return $data; } /** * Extract person/author fields from the post author. * * @param int $post_id WordPress post ID. * @param string $schema_type Schema.org type. * @param array $ai_entities AI-detected entities. * @return array Person/author field data. */ public function extract_person_fields( $post_id, $schema_type, $ai_entities = array() ) { $data = array(); // Author for Article types. $author_types = array( 'Article', 'BlogPosting', 'NewsArticle', 'Review', 'Recipe', 'HowTo' ); if ( ! in_array( $schema_type, $author_types, true ) ) { return $data; } // AI entities first. if ( ! empty( $ai_entities['author'] ) ) { if ( is_array( $ai_entities['author'] ) ) { $data['author'] = array_merge( array( '@type' => 'Person' ), $ai_entities['author'] ); } else { $data['author'] = array( '@type' => 'Person', 'name' => sanitize_text_field( $ai_entities['author'] ), ); } return $data; } // WordPress post author, but only for a specific named individual. // Schema_AI_Base_Schema::get_author_reference() already applies this // same check and deliberately leaves "author" unset for a generic or // shared account; without this same gate here, merge_fields() (which // only fills a key when the builder left it unset) would silently // fill it back in with a full inline Person built from that account. $post = get_post( $post_id ); if ( $post && $post->post_author && ( ! class_exists( 'Schema_AI_Author_Utils' ) || Schema_AI_Author_Utils::is_named_individual( $post->post_author ) ) ) { $author_id = $post->post_author; $author = get_userdata( $author_id ); if ( $author ) { $author_data = array( '@type' => 'Person', 'name' => $author->display_name, 'url' => get_author_posts_url( $author_id ), ); // Author avatar. $avatar_url = get_avatar_url( $author_id, array( 'size' => 96 ) ); if ( $avatar_url ) { $author_data['image'] = $avatar_url; } // Author description. $bio = get_the_author_meta( 'description', $author_id ); if ( ! empty( $bio ) ) { $author_data['description'] = sanitize_text_field( $bio ); } // Social links from user meta. $social_fields = array( 'url' => 'url', 'twitter' => 'sameAs', ); $same_as = array(); $user_url = get_the_author_meta( 'user_url', $author_id ); if ( ! empty( $user_url ) ) { $same_as[] = esc_url( $user_url ); } $twitter = get_the_author_meta( 'twitter', $author_id ); if ( ! empty( $twitter ) ) { $same_as[] = 'https://twitter.com/' . sanitize_text_field( ltrim( $twitter, '@' ) ); } if ( ! empty( $same_as ) ) { $author_data['sameAs'] = $same_as; } $data['author'] = $author_data; } } // Publisher for Article types (uses site info). $article_types = array( 'Article', 'BlogPosting', 'NewsArticle' ); if ( in_array( $schema_type, $article_types, true ) ) { $settings = get_option( 'schema_ai_settings', array() ); $publisher = array( '@type' => 'Organization', 'name' => get_bloginfo( 'name' ), 'url' => home_url( '/' ), ); // Site logo. $custom_logo_id = get_theme_mod( 'custom_logo' ); if ( $custom_logo_id ) { $logo_src = wp_get_attachment_image_src( $custom_logo_id, 'full' ); if ( $logo_src ) { $publisher['logo'] = array( '@type' => 'ImageObject', 'url' => $logo_src[0], 'width' => $logo_src[1], 'height' => $logo_src[2], ); } } elseif ( ! empty( $settings['default_logo'] ) ) { $publisher['logo'] = array( '@type' => 'ImageObject', 'url' => $settings['default_logo'], ); } $data['publisher'] = $publisher; } return $data; } /** * Clean and validate extracted data. * * Removes empty values and ensures required fields exist for the target * schema type. * * @param array $data Extracted field data. * @param string $schema_type Schema.org type. * @return array Cleaned data. */ public function clean_and_validate( $data, $schema_type ) { // Remove empty values recursively. $data = $this->remove_empty( $data ); // Ensure required fields have fallback values. $required_map = array( 'Article' => array( 'headline', 'description' ), 'BlogPosting' => array( 'headline', 'description' ), 'NewsArticle' => array( 'headline', 'description' ), 'WebPage' => array( 'name', 'description' ), 'Product' => array( 'name' ), 'Recipe' => array( 'name' ), 'Event' => array( 'name' ), 'FAQPage' => array(), 'HowTo' => array( 'name' ), 'LocalBusiness' => array( 'name' ), 'Organization' => array( 'name' ), 'Person' => array( 'name' ), 'Review' => array(), 'Service' => array( 'name' ), 'VideoObject' => array( 'name' ), 'ImageObject' => array( 'name' ), 'Course' => array( 'name' ), ); if ( isset( $required_map[ $schema_type ] ) ) { foreach ( $required_map[ $schema_type ] as $field ) { if ( empty( $data[ $field ] ) ) { // Provide a minimal fallback to prevent validation errors. $data[ $field ] = ''; } } } return $data; } /** * Format a price range string from an array of prices. * * @param array $prices Array of numeric price values. * @return string Price range string (e.g. "$10 - $50"). */ public function format_price_range( $prices ) { if ( ! is_array( $prices ) || empty( $prices ) ) { return ''; } $numeric = array_filter( $prices, 'is_numeric' ); if ( empty( $numeric ) ) { return ''; } $min = min( $numeric ); $max = max( $numeric ); if ( $min === $max ) { return '$' . number_format( (float) $min, 2 ); } return '$' . number_format( (float) $min, 2 ) . ' - $' . number_format( (float) $max, 2 ); } /** * Recursively remove empty values from an array. * * Keeps values of 0 and false; only removes empty strings, null, and * empty arrays. * * @param array $data The data array. * @return array Cleaned array. */ private function remove_empty( $data ) { foreach ( $data as $key => $value ) { if ( is_array( $value ) ) { $data[ $key ] = $this->remove_empty( $value ); if ( empty( $data[ $key ] ) ) { unset( $data[ $key ] ); } } elseif ( is_null( $value ) || ( is_string( $value ) && '' === $value ) ) { unset( $data[ $key ] ); } } return $data; } }