> */ public static function items( int $post_id ): array { $stored = get_post_meta( $post_id, self::META_ITEMS, true ); if ( is_array( $stored ) && ! empty( $stored ) ) { return array_values( $stored ); } // Migrate the single-schema format from earlier versions. $legacy_type = (string) get_post_meta( $post_id, '_airanksuite_schema_type', true ); if ( '' !== $legacy_type && 'auto' !== $legacy_type ) { $legacy_data = get_post_meta( $post_id, '_airanksuite_schema_data', true ); return array( array( 'type' => $legacy_type, 'data' => is_array( $legacy_data ) ? $legacy_data : array(), ), ); } return array(); } /** * Persist items, keeping only fields the chosen type declares. * * @param array $items Raw items. * @return array> */ public static function save( int $post_id, array $items ): array { $clean = array(); foreach ( array_slice( $items, 0, 20 ) as $item ) { if ( ! is_array( $item ) ) { continue; } $type = sanitize_text_field( (string) ( $item['type'] ?? '' ) ); if ( '' === $type || 'auto' === $type || ! SchemaTypes::exists( $type ) ) { continue; } $allowed = array_column( SchemaTypes::fields( $type ), 'key' ); $data = array(); foreach ( (array) ( $item['data'] ?? array() ) as $key => $value ) { if ( in_array( $key, $allowed, true ) ) { // %category% and %date% are offered to the user by the editor's own // variable list, and sanitize_textarea_field() strips percent-octets, // turning them into "tegory%" and "te%". The global template path // already knew this; the per-post path did not. $data[ sanitize_key( $key ) ] = \AiRankSuite\Support\Sanitize::template_multiline( (string) $value ); } } $clean[] = array( 'type' => $type, 'data' => $data, ); } if ( empty( $clean ) ) { delete_post_meta( $post_id, self::META_ITEMS ); } else { update_post_meta( $post_id, self::META_ITEMS, $clean ); } // The usage counts on the Schema screen are cached; a change here is // exactly what moves them. delete_transient( 'airanksuite_schema_usage' ); delete_post_meta( $post_id, '_airanksuite_schema_type' ); delete_post_meta( $post_id, '_airanksuite_schema_data' ); return $clean; } /** * Build every node for a post (own items + matching global templates). * * @return array> */ public function build_for_post( WP_Post $post, string $url, string $org_id, string $site_id ): array { $items = self::items( $post->ID ); foreach ( SchemaTemplates::matching( $post ) as $template ) { // A manual item of the same type always wins over a template. $has_type = false; foreach ( $items as $item ) { if ( $item['type'] === $template['type'] ) { $has_type = true; break; } } if ( ! $has_type ) { $items[] = array( 'type' => (string) $template['type'], 'data' => (array) $template['data'], ); } } $nodes = array(); foreach ( $items as $index => $item ) { $node = $this->build( (string) $item['type'], (array) $item['data'], $post, $url, $org_id, $index ); if ( null !== $node ) { $node['isPartOf'] = array( '@id' => $site_id ); $node['mainEntityOfPage'] = array( '@id' => $url . '#webpage' ); $nodes[] = $node; } } // Blocks on the page speak for themselves: an FAQ block is a FAQPage, // a how-to block is a HowTo. Compared against what was actually built, // not against what was configured — a hand-written item that produced // nothing (a required field left empty) must not silently delete the // node the page's own content would have printed. $built = array_flip( array_filter( array_column( $nodes, '@type' ) ) ); // A video embedded in the page implies a VideoObject, the same way an // FAQ block implies a FAQPage — and the same rule applies: only when // nothing else already produced one. $detected = SchemaTypes::detect_video_node( $post ); if ( null !== $detected && ! isset( $built['VideoObject'] ) ) { $detected['isPartOf'] = array( '@id' => $site_id ); $detected['mainEntityOfPage'] = array( '@id' => $url . '#webpage' ); $nodes[] = $detected; $built['VideoObject'] = true; } foreach ( \AiRankSuite\Modules\Blocks\Services\BlockSchema::for_post( $post ) as $node ) { if ( isset( $built[ (string) ( $node['@type'] ?? '' ) ] ) ) { continue; } $node['isPartOf'] = array( '@id' => $site_id ); $node['mainEntityOfPage'] = array( '@id' => $url . '#webpage' ); $nodes[] = $node; } return $nodes; } /** * Build one node. * * @param array $data Field values. * @return array|null */ public function build( string $type, array $data, WP_Post $post, string $url, string $org_id, int $index = 0 ): ?array { if ( ! SchemaTypes::exists( $type ) || 'auto' === $type ) { return null; } $definition = SchemaTypes::all()[ $type ]; $node = array( '@type' => $type, '@id' => $url . '#' . strtolower( $type ) . ( $index > 0 ? '-' . $index : '' ), 'url' => $url, 'name' => wp_strip_all_tags( get_the_title( $post ) ), ); $description = (string) get_post_meta( $post->ID, '_airanksuite_seo_desc', true ); if ( '' === trim( $description ) ) { $description = (string) get_the_excerpt( $post ); } if ( '' !== trim( $description ) ) { $node['description'] = wp_strip_all_tags( $description ); } $image = get_the_post_thumbnail_url( $post, 'full' ); if ( $image ) { $node['image'] = (string) $image; } // Article-like types carry authorship and dates by default. if ( 'article' === ( $definition['base'] ?? 'thing' ) ) { $node['headline'] = $node['name']; $node['datePublished'] = (string) get_post_time( 'c', true, $post ); $node['dateModified'] = (string) get_post_modified_time( 'c', true, $post ); $author = get_the_author_meta( 'display_name', (int) $post->post_author ); if ( '' !== $author ) { $node['author'] = array( '@type' => 'Person', 'name' => $author, ); } $node['publisher'] = array( '@id' => $org_id ); } // A job posting is dated by when it was posted, which is the post's own // date; Google marks the report incomplete without it. if ( 'JobPosting' === $type ) { $node['datePosted'] = (string) get_post_time( 'c', true, $post ); } foreach ( (array) $definition['fields'] as $field ) { $raw = trim( (string) ( $data[ $field['key'] ] ?? '' ) ); if ( '' === $raw ) { continue; } $value = $this->transform( $raw, (string) $field['transform'], $post, $org_id ); if ( null === $value || array() === $value ) { continue; } $this->set_path( $node, (string) $field['prop'], $value ); } // Type-specific fallbacks that need real context. if ( 'VideoObject' === $type && empty( $node['embedUrl'] ) ) { $embed = SchemaTypes::detect_video( $post ); if ( null !== $embed ) { $node['embedUrl'] = $embed; } } if ( isset( $node['aggregateRating'] ) && is_array( $node['aggregateRating'] ) ) { $node['aggregateRating'] = array_merge( array( '@type' => 'AggregateRating', 'bestRating' => '5', 'worstRating' => '1', ), $node['aggregateRating'] ); } foreach ( array( 'offers' => 'Offer', 'address' => 'PostalAddress', 'geo' => 'GeoCoordinates', 'nutrition' => 'NutritionInformation', 'estimatedCost' => 'MonetaryAmount', 'reviewRating' => 'Rating', 'baseSalary' => 'MonetaryAmount', 'location' => 'Place', 'speakable' => 'SpeakableSpecification', 'distribution' => 'DataDownload', 'partOfSeries' => 'PodcastSeries', 'associatedMedia' => 'AudioObject', 'mileageFromOdometer' => 'QuantitativeValue', 'itemReviewed' => 'Thing', 'hasCourseInstance' => 'CourseInstance', 'jobLocation' => 'Place', 'mainEntity' => 'Question' ) as $key => $sub_type ) { if ( isset( $node[ $key ] ) && is_array( $node[ $key ] ) && ! isset( $node[ $key ]['@type'] ) && ! isset( $node[ $key ][0] ) ) { $node[ $key ] = array_merge( array( '@type' => $sub_type ), $node[ $key ] ); } } if ( isset( $node['baseSalary']['value'] ) && is_array( $node['baseSalary']['value'] ) ) { $node['baseSalary']['value'] = array_merge( array( '@type' => 'QuantitativeValue' ), $node['baseSalary']['value'] ); } if ( isset( $node['offers']['price'] ) && empty( $node['offers']['priceCurrency'] ) ) { $node['offers']['priceCurrency'] = function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'EUR'; } if ( isset( $node['offers'] ) && is_array( $node['offers'] ) && empty( $node['offers']['url'] ) ) { $node['offers']['url'] = $url; } /** * Filter a single schema node before it enters the graph. * * @param array $node The node. * @param string $type Schema type. * @param WP_Post $post The post. */ return (array) apply_filters( 'airanksuite/schema/node', $this->prune( $node ), $type, $post ); } /** * Resolve template variables against a post. */ public static function resolve_variables( string $value, WP_Post $post ): string { if ( ! str_contains( $value, '%' ) ) { return $value; } $description = (string) get_post_meta( $post->ID, '_airanksuite_seo_desc', true ); if ( '' === trim( $description ) ) { $description = (string) get_the_excerpt( $post ); } $category = ''; $terms = get_the_terms( $post, 'category' ); if ( is_array( $terms ) && ! empty( $terms ) ) { $category = (string) $terms[0]->name; } $price = ''; $sku = ''; if ( function_exists( 'wc_get_product' ) ) { $product = wc_get_product( $post->ID ); if ( $product ) { $price = (string) $product->get_price(); $sku = (string) $product->get_sku(); } } return strtr( $value, array( '%title%' => wp_strip_all_tags( get_the_title( $post ) ), '%excerpt%' => wp_strip_all_tags( $description ), '%permalink%' => (string) get_permalink( $post ), '%image%' => (string) get_the_post_thumbnail_url( $post, 'full' ), '%author%' => (string) get_the_author_meta( 'display_name', (int) $post->post_author ), '%date%' => (string) get_post_time( 'c', true, $post ), '%modified%' => (string) get_post_modified_time( 'c', true, $post ), '%sitename%' => (string) get_bloginfo( 'name' ), '%category%' => $category, '%price%' => $price, '%sku%' => $sku, ) ); } /** * Apply a transformer to a resolved value. * * @return mixed */ private function transform( string $raw, string $transform, WP_Post $post, string $org_id ) { $value = self::resolve_variables( $raw, $post ); if ( '' === trim( $value ) ) { return null; } $lines = static fn( string $v ): array => array_values( array_filter( array_map( 'trim', preg_split( '/\r\n|\r|\n/', $v ) ?: array() ) ) ); switch ( $transform ) { case 'number': return is_numeric( $value ) ? 0 + $value : $value; case 'url': return esc_url_raw( $value ); case 'date': $time = strtotime( $value ); return false === $time ? null : gmdate( 'c', $time ); case 'duration': return self::to_iso_duration( $value ); case 'list': return $lines( $value ); case 'named_list': return array_map( static fn( string $name ): array => array( '@type' => 'HowToSupply', 'name' => $name, ), $lines( $value ) ); case 'steps': $steps = array(); foreach ( $lines( $value ) as $i => $text ) { $steps[] = array( '@type' => 'HowToStep', 'position' => $i + 1, 'text' => $text, ); } return $steps; case 'faq': $faqs = array(); foreach ( $lines( $value ) as $line ) { $parts = array_map( 'trim', explode( '|', $line, 2 ) ); if ( count( $parts ) < 2 || '' === $parts[0] || '' === $parts[1] ) { continue; } $faqs[] = array( '@type' => 'Question', 'name' => $parts[0], 'acceptedAnswer' => array( '@type' => 'Answer', 'text' => $parts[1], ), ); } return $faqs; case 'item_list': $items = array(); foreach ( $lines( $value ) as $i => $line ) { $parts = array_map( 'trim', explode( '|', $line, 2 ) ); $items[] = array_filter( array( '@type' => 'ListItem', 'position' => $i + 1, 'name' => $parts[0], 'url' => isset( $parts[1] ) ? esc_url_raw( $parts[1] ) : null, ) ); } return $items; case 'brand': return array( '@type' => 'Brand', 'name' => $value, ); case 'person': return array( '@type' => 'Person', 'name' => $value, ); case 'country': return array( '@type' => 'Country', 'name' => $value, ); case 'identifier': return array( '@type' => 'PropertyValue', 'name' => (string) get_bloginfo( 'name' ), 'value' => $value, ); case 'bool': return in_array( strtolower( $value ), array( 'true', '1', 'yes' ), true ); case 'organization': return array( '@type' => 'Organization', 'name' => $value, ); case 'schema_url': return 'https://schema.org/' . $value; case 'attendance': return 'https://schema.org/' . $value . 'EventAttendanceMode'; case 'event_status': return 'https://schema.org/Event' . $value; default: return $value; } } /** * Accept human input ("20 min", "1h 30m") as well as raw ISO 8601. */ public static function to_iso_duration( string $value ): string { $value = trim( $value ); if ( preg_match( '/^P(T.*)?$/i', $value ) || str_starts_with( strtoupper( $value ), 'PT' ) ) { return strtoupper( $value ); } $weeks = 0; $days = 0; $hours = 0; $mins = 0; $secs = 0; if ( preg_match_all( '/(\d+(?:[.,]\d+)?)\s*(weeks?|wochen?|w|days?|tage?n?|d|hours?|stunden?|hrs?|h|minutes?|minuten?|mins?|m|seconds?|sekunden?|secs?|s)\b/iu', $value, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $match ) { $amount = (int) round( (float) str_replace( ',', '.', $match[1] ) ); $unit = strtolower( $match[2] ); if ( str_starts_with( $unit, 'w' ) ) { $weeks += $amount; } elseif ( str_starts_with( $unit, 'd' ) || str_starts_with( $unit, 't' ) ) { $days += $amount; } elseif ( str_starts_with( $unit, 'h' ) || str_starts_with( $unit, 'std' ) ) { $hours += $amount; } elseif ( str_starts_with( $unit, 's' ) ) { $secs += $amount; } else { $mins += $amount; } } } elseif ( is_numeric( $value ) ) { $mins = (int) $value; } else { return $value; } $date = ( $weeks > 0 ? $weeks . 'W' : '' ) . ( $days > 0 ? $days . 'D' : '' ); $time = ( $hours > 0 ? $hours . 'H' : '' ) . ( $mins > 0 ? $mins . 'M' : '' ) . ( $secs > 0 ? $secs . 'S' : '' ); if ( '' === $date && '' === $time ) { return $value; } return 'P' . $date . ( '' !== $time ? 'T' . $time : '' ); } /** * Validate a type's data against required and recommended fields. * * @param array $data Field values. * @return array{missing_required: array, missing_recommended: array, valid: bool} */ public static function validate( string $type, array $data ): array { $required = array(); $recommended = array(); foreach ( SchemaTypes::fields( $type ) as $field ) { $value = trim( (string) ( $data[ $field['key'] ] ?? '' ) ); if ( '' !== $value ) { continue; } if ( ! empty( $field['required'] ) ) { $required[] = (string) $field['label']; } elseif ( ! empty( $field['recommended'] ) ) { $recommended[] = (string) $field['label']; } } return array( 'missing_required' => $required, 'missing_recommended' => $recommended, 'valid' => empty( $required ), ); } /** * Write a value into a nested array using a dot path. * * @param array $node Node (by reference). * @param mixed $value Value. */ private function set_path( array &$node, string $path, $value ): void { $segments = explode( '.', $path ); $cursor = &$node; foreach ( $segments as $i => $segment ) { if ( $i === count( $segments ) - 1 ) { $cursor[ $segment ] = $value; break; } if ( ! isset( $cursor[ $segment ] ) || ! is_array( $cursor[ $segment ] ) ) { $cursor[ $segment ] = array(); } $cursor = &$cursor[ $segment ]; } unset( $cursor ); } /** * Drop empty branches so the output stays clean. * * @param array $node Node. * @return array */ private function prune( array $node ): array { foreach ( $node as $key => $value ) { if ( is_array( $value ) ) { $node[ $key ] = $this->prune( $value ); if ( array() === $node[ $key ] ) { unset( $node[ $key ] ); } continue; } if ( null === $value || '' === $value ) { unset( $node[ $key ] ); } } return $node; } }