should_auto_apply( $post ) ) { return; } $this->generate_for_post( $post->ID ); } catch ( \Exception $e ) { // Log silently — never block publishing. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( 'Schema AI Auto-Apply error on publish: ' . $e->getMessage() ); } } } /** * Whether generating on publish is switched on. * * The Settings page has always shown a "when a post is published" tick * box, but until 1.0.37 nothing read it: the only switch that worked was * the setup wizard's `enable_auto_apply`. Once the Settings page or the * wizard has been saved by a version that knows this * (`auto_generate_explicit`), the tick box is the truth. Before that, a * site keeps what it had: on if the wizard switched it on, or if the box * was ticked expecting it to work. * * Shared with the Settings page and the wizard, so the box always shows * what will actually happen. * * @param array $settings The schema_ai_settings option. * @return bool */ public static function is_enabled( $settings ) { if ( ! empty( $settings['auto_generate_explicit'] ) ) { return ! empty( $settings['auto_generate_publish'] ); } return ! empty( $settings['enable_auto_apply'] ) || ! empty( $settings['auto_generate_publish'] ); } /** * Post types it applies to: the list chosen in the wizard or on * the Settings page, or posts and pages when nothing has been chosen. * * @param array $settings The schema_ai_settings option. * @return string[] */ public static function get_post_types( $settings ) { if ( ! empty( $settings['auto_generate_post_types'] ) && is_array( $settings['auto_generate_post_types'] ) ) { return $settings['auto_generate_post_types']; } return array( 'post', 'page' ); } /** * Determine whether auto-apply should run for a given post. * * Checks that it is enabled in settings and that the post type is in the * configured list. * * @param WP_Post $post Post object. * @return bool */ public function should_auto_apply( $post ) { if ( ! $post || ! is_object( $post ) ) { return false; } $settings = get_option( 'schema_ai_settings', array() ); if ( ! is_array( $settings ) ) { $settings = array(); } if ( ! self::is_enabled( $settings ) ) { return false; } if ( ! in_array( $post->post_type, self::get_post_types( $settings ), true ) ) { return false; } // Skip if user does not have permission. if ( ! current_user_can( 'edit_post', $post->ID ) ) { return false; } return true; } /** * Generate schema for a single post. * * Flow: * 1. Page Analyzer → classify page type (12 named types) * 2. Decision Engine → get ordered list of schema types for that page type * 3. Schema Generator → build each type using proper builders + @id linking * 4. Persist each schema as a separate row; delete stale auto-generated rows * 5. Update content hash and invalidate renderer cache * * @param int $post_id Post ID. * @return bool True on success, false on failure. */ public function generate_for_post( $post_id ) { if ( self::$is_generating ) { return false; } $post = get_post( $post_id ); if ( ! $post ) { return false; } self::$is_generating = true; try { // Classify the page. $analyzer = new Schema_AI_Page_Analyzer(); $page_type = $analyzer->classify( $post_id ); $schema_types = Schema_AI_Schema_Decision_Engine::get_schema_types( $page_type ); global $wpdb; $table = esc_sql( $wpdb->prefix . 'schema_ai_schemas' ); // Delete all previously auto-generated schemas for this post so we // start fresh. Manual (is_auto_generated=0) schemas are preserved. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Write op; custom table; no WP API alternative. $wpdb->delete( $table, array( 'post_id' => $post_id, 'is_auto_generated' => 1, ), array( '%d', '%d' ) ); // legal_page → no schema output. We are done after deleting stale rows. if ( empty( $schema_types ) ) { $this->finalise( $post_id, $post ); return true; } // Build all schemas first, then validate the full @graph before persisting. $generator = new Schema_AI_Schema_Generator(); $built = array(); foreach ( $schema_types as $schema_type ) { try { $result = $generator->generate( $post_id, $schema_type ); } catch ( \Exception $e ) { // Unsupported type — skip silently. continue; } if ( empty( $result['schema'] ) ) { continue; } $built[] = array( 'schema_type' => $schema_type, 'result' => $result, ); } // Link WebPage -> BreadcrumbList / FAQPage now that the whole batch // is known. A single builder only sees its own post_id, not which // sibling types are being generated alongside it, so it can't // safely reference a BreadcrumbList or FAQPage that might not // exist this batch (the homepage, for example, never gets a // BreadcrumbList per the decision engine's matrix). Do it here // instead, once both sides of each link are confirmed present. // AboutPage/ContactPage are WebPage subtypes built from the same // Schema_AI_WebPage_Schema class (see Schema_AI_Schema_Factory), // just with @type overridden afterward: they fill the same // "this page's own wrapper node" role as a literal WebPage entry, // so they must be recognized here too or the breadcrumb/subjectOf // link silently never gets attached on About/Contact pages. $webpage_types = array( 'WebPage', 'AboutPage', 'ContactPage' ); $webpage_index = null; $breadcrumb_index = null; $faq_index = null; $article_index = null; foreach ( $built as $index => $item ) { if ( in_array( $item['schema_type'], $webpage_types, true ) ) { $webpage_index = $index; } elseif ( 'BreadcrumbList' === $item['schema_type'] ) { $breadcrumb_index = $index; } elseif ( 'FAQPage' === $item['schema_type'] ) { $faq_index = $index; } elseif ( in_array( $item['schema_type'], array( 'Article', 'BlogPosting', 'NewsArticle' ), true ) ) { $article_index = $index; } } if ( null !== $webpage_index && null !== $breadcrumb_index ) { $built[ $webpage_index ]['result']['schema']['breadcrumb'] = Schema_AI_ID_Builder::ref( Schema_AI_ID_Builder::breadcrumb( $post_id ) ); } if ( null !== $webpage_index && null !== $faq_index ) { $built[ $webpage_index ]['result']['schema']['subjectOf'] = Schema_AI_ID_Builder::ref( Schema_AI_ID_Builder::faq_page( $post_id ) ); } // Build a real Person entity for the article's author @id, but // only when get_author_reference() actually set one (it already // checks Schema_AI_Author_Utils::is_named_individual() and skips // generic/team accounts). Without this, "author" pointed at a // Person that was never built anywhere, a dangling reference on // every single Article/BlogPosting/NewsArticle post. if ( null !== $article_index && ! empty( $built[ $article_index ]['result']['schema']['author']['@id'] ) ) { $author_id = (int) get_post_field( 'post_author', $post_id ); if ( $author_id ) { $person_schema = array( '@type' => 'Person', '@id' => Schema_AI_ID_Builder::person( $author_id ), 'name' => get_the_author_meta( 'display_name', $author_id ), 'url' => get_author_posts_url( $author_id ), ); $bio = get_the_author_meta( 'description', $author_id ); if ( ! empty( $bio ) ) { $person_schema['description'] = $bio; } $built[] = array( 'schema_type' => 'Person', 'result' => array( 'schema' => $person_schema, 'validation' => array( 'valid' => true, 'errors' => array(), 'warnings' => array(), ), 'confidence' => null, ), ); } } // @id cross-reference check across the full entity set. $graph_has_errors = false; if ( ! empty( $built ) && class_exists( 'Schema_AI_Schema_Validator' ) ) { $entity_schemas = array(); foreach ( $built as $item ) { $entity_schemas[] = $item['result']['schema']; } $validator = new Schema_AI_Schema_Validator(); $graph_check = $validator->validate_graph( $entity_schemas ); $graph_has_errors = ! $graph_check['valid']; if ( $graph_has_errors && defined( 'WP_DEBUG' ) && WP_DEBUG ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( 'Schema AI @graph validation (post ' . $post_id . '): ' . implode( '; ', $graph_check['errors'] ) ); } } // Persist each schema with the correct validation status. foreach ( $built as $item ) { $schema_type = $item['schema_type']; $result = $item['result']; $individual_valid = ! empty( $result['validation'] ) && $result['validation']['valid']; if ( $graph_has_errors ) { $validation_status = 'warning'; } elseif ( $individual_valid ) { $validation_status = 'valid'; } else { $validation_status = 'pending'; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Write op; custom table. $wpdb->insert( $table, array( 'post_id' => $post_id, 'schema_type' => $schema_type, 'schema_data' => wp_json_encode( $result['schema'] ), 'is_auto_generated' => 1, 'confidence_score' => isset( $result['confidence'] ) ? (float) $result['confidence'] : 0.9, 'validation_status' => $validation_status, ), array( '%d', '%s', '%s', '%d', '%f', '%s' ) ); } $this->finalise( $post_id, $post ); return true; } catch ( \Exception $e ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( 'Schema AI Auto-Apply generate error: ' . $e->getMessage() ); } return false; } finally { self::$is_generating = false; } } /** * Update content hash and invalidate renderer cache after generation. * * @param int $post_id Post ID. * @param WP_Post $post Post object. * @return void */ private function finalise( $post_id, $post ) { update_post_meta( $post_id, self::CONTENT_HASH_META, $this->compute_content_hash( $post ) ); if ( class_exists( 'Schema_AI_Schema_Cache' ) ) { $cache = new Schema_AI_Schema_Cache(); $cache->invalidate( $post_id ); } } /** * Compute a hash of the post's title and content. * * @param WP_Post $post Post object. * @return string MD5 hash. */ private function compute_content_hash( $post ) { return md5( $post->post_title . $post->post_content ); } }