PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 2.10.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v2.10.0
2.11.0 2.10.0 2.9.0 2.8.0 2.7.0 2.6.0 2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 1.26.0 1.25.0 trunk 1.0.0 All 52 releases
← All changes | includes/seo/class-schema-management-system.php +667 -47 2.0.1 → 2.10.0 View file →
@@ -167,8 +167,20 @@
167 167 'rich_snippets' => ['video', 'video_carousel'],
168 168 'context_types' => ['post', 'page'],
169 169 'priority' => 'medium'
170 170 ],
171 + // Offered by the metabox dropdown and registered in Schema_Factory, but
172 + // absent here — generate_schema_markup() keys off this array, so a
173 + // Review request was silently skipped (#462).
174 + 'Review' => [
175 + 'name' => 'Review',
176 + 'description' => 'Reviews and ratings of a product, service or place',
177 + 'required_properties' => ['itemReviewed', 'reviewRating', 'author'],
178 + 'recommended_properties' => ['reviewBody', 'datePublished', 'publisher'],
179 + 'rich_snippets' => ['review', 'review_snippet'],
180 + 'context_types' => ['post', 'page'],
181 + 'priority' => 'medium'
182 + ],
171 183 'Recipe' => [
172 184 'name' => 'Recipe',
173 185 'description' => 'Cooking recipes and food preparation',
174 186 'required_properties' => ['name', 'image', 'author', 'datePublished', 'description', 'recipeIngredient', 'recipeInstructions'],
@@ -189,13 +201,43 @@
189 201 'WebPage' => [
190 202 'name' => 'WebPage',
191 203 'description' => 'Individual web pages',
192 204 'required_properties' => ['name', 'url'],
205 + // 'post' as well as 'page': the per-page selector reaches this for
206 + // any post type, and a registry limited to 'page' silently produced
207 + // nothing for the rest (#624).
193 208 'recommended_properties' => ['description', 'author', 'datePublished', 'breadcrumb'],
194 209 'rich_snippets' => ['webpage', 'breadcrumb'],
195 - 'context_types' => ['page'],
210 + 'context_types' => ['page', 'post'],
196 211 'priority' => 'medium'
197 212 ],
213 + 'AboutPage' => [
214 + 'name' => 'AboutPage',
215 + 'description' => 'A page describing the organisation or person behind the site',
216 + 'required_properties' => ['name', 'url'],
217 + 'recommended_properties' => ['description', 'author', 'datePublished', 'breadcrumb'],
218 + 'rich_snippets' => ['webpage', 'breadcrumb'],
219 + 'context_types' => ['page', 'post'],
220 + 'priority' => 'medium'
221 + ],
222 + 'ContactPage' => [
223 + 'name' => 'ContactPage',
224 + 'description' => 'A page giving contact details',
225 + 'required_properties' => ['name', 'url'],
226 + 'recommended_properties' => ['description', 'author', 'datePublished', 'breadcrumb'],
227 + 'rich_snippets' => ['webpage', 'breadcrumb'],
228 + 'context_types' => ['page', 'post'],
229 + 'priority' => 'medium'
230 + ],
231 + 'ProfilePage' => [
232 + 'name' => 'ProfilePage',
233 + 'description' => 'A page about a single person or organisation',
234 + 'required_properties' => ['name', 'url'],
235 + 'recommended_properties' => ['description', 'author', 'datePublished', 'breadcrumb'],
236 + 'rich_snippets' => ['webpage', 'breadcrumb'],
237 + 'context_types' => ['page', 'post'],
238 + 'priority' => 'medium'
239 + ],
198 240 'FAQPage' => [
199 241 'name' => 'FAQPage',
200 242 'description' => 'Frequently Asked Questions pages',
201 243 'required_properties' => ['mainEntity'],
@@ -309,8 +351,19 @@
309 351 */
310 352 private ?Schema_Cache_Manager $cache_manager = null;
311 353
312 354 /**
355 + * Whether the foreign-settings listener has been registered this request.
356 + *
357 + * Static because `thinkrank_seo_settings_saved` is a global hook — one
358 + * listener serves every instance. See the constructor for why (#463).
359 + *
360 + * @since 1.16.0
361 + * @var bool
362 + */
363 + private static bool $foreign_settings_listener_registered = false;
364 +
365 + /**
313 366 * Constructor
314 367 *
315 368 * @since 1.0.0
316 369 */
@@ -326,11 +379,117 @@
326 379 $this->initialize_schema_builder();
327 380
328 381 // Initialize Schema Cache Manager for performance optimization
329 382 $this->initialize_cache_manager();
383 +
384 + // LocalBusiness and Organization both read Business Info, which Site
385 + // Identity owns. Without this, editing an address or phone number never
386 + // refreshed the deployed schema (#455).
387 + //
388 + // Registered at most once per request. WordPress keys callbacks by
389 + // object hash, so binding $this here added a fresh listener for every
390 + // instance — and this class is constructed from inside the very callback
391 + // it registers, which doubled the listener count on every settings save
392 + // (#463). The guard is static because the hook itself is global.
393 + if (!self::$foreign_settings_listener_registered) {
394 + self::$foreign_settings_listener_registered = true;
395 + add_action('thinkrank_seo_settings_saved', [$this, 'refresh_schema_for_foreign_settings'], 10, 4);
396 + }
330 397 }
331 398
332 399 /**
400 + * Regenerate schema when another manager saves settings this schema reads.
401 + *
402 + * Site Identity owns the Business Info fields that feed LocalBusiness and
403 + * the Organization address/contactPoint, so a save there has to refresh the
404 + * deployed schema even though no schema setting changed.
405 + *
406 + * @since 2.0.2
407 + *
408 + * @param string $manager_type Settings category that was saved.
409 + * @param array $settings Settings that were written.
410 + * @param string $context_type Context type.
411 + * @param int|null $context_id Context ID.
412 + * @return void
413 + */
414 + public function refresh_schema_for_foreign_settings(
415 + string $manager_type,
416 + array $settings,
417 + string $context_type,
418 + ?int $context_id
419 + ): void {
420 + if ('site_identity' !== $manager_type) {
421 + return;
422 + }
423 +
424 + $business_keys = [
425 + 'business_name', 'business_type', 'business_address', 'business_city',
426 + 'business_state', 'business_postal_code', 'business_country',
427 + 'business_phone', 'business_email', 'business_hours',
428 + 'business_latitude', 'business_longitude', 'business_price_range',
429 + ];
430 +
431 + // Which deployed types a Site Identity key can invalidate. The business
432 + // block feeds LocalBusiness and Organization; alternate_name feeds the
433 + // WebSite node, which had no entry here at all — so editing it left the
434 + // deployed schema showing the previous value until something else
435 + // happened to redeploy (#692).
436 + $refresh_types = [];
437 +
438 + if (!empty(array_intersect_key($settings, array_flip($business_keys)))) {
439 + $refresh_types[] = 'LocalBusiness';
440 + $refresh_types[] = 'Organization';
441 + }
442 +
443 + if (array_key_exists('alternate_name', $settings)) {
444 + $refresh_types[] = 'WebSite';
445 + }
446 +
447 + if (empty($refresh_types)) {
448 + return;
449 + }
450 +
451 + $schema_settings = $this->get_settings($context_type, $context_id);
452 + if (empty($schema_settings['auto_deploy'])) {
453 + return;
454 + }
455 +
456 + // Only refresh types that are actually deployed, so this never adds a
457 + // type the admin did not enable.
458 + $deployed = array_keys((array) $this->get_deployed_schemas($context_type, $context_id));
459 + $affected = array_values(array_intersect($deployed, $refresh_types));
460 +
461 + if (empty($affected)) {
462 + return;
463 + }
464 +
465 + try {
466 + $generation = $this->generate_schema_markup($context_type, $context_id, $affected);
467 +
468 + // Deploy the types that validated, not all-or-nothing. Gating on
469 + // deployment_ready meant one invalid type blocked every valid one
470 + // in the same batch (#470).
471 + $deployable = [];
472 + foreach ($affected as $type) {
473 + if (!empty($generation['generated_schemas'][$type])
474 + && !empty($generation['validation_results'][$type]['is_valid'])
475 + ) {
476 + $deployable[$type] = $generation['generated_schemas'][$type];
477 + }
478 + }
479 +
480 + if (!empty($deployable)) {
481 + $this->deploy_schema_markup($context_type, $context_id, $deployable);
482 + }
483 + } catch (\Exception $e) {
484 + if (defined('WP_DEBUG') && WP_DEBUG) {
485 + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
486 + error_log('ThinkRank: Business Info schema refresh failed: ' . $e->getMessage());
487 + }
488 + }
489 + }
490 +
491 + /**
333 492 * Initialize Schema Builder
334 493 *
335 494 * @return void
336 495 */
@@ -356,10 +515,20 @@
356 515 require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-schema-cache-manager.php';
357 516 }
358 517
359 518 if (class_exists('ThinkRank\\SEO\\Schema_Cache_Manager')) {
360 - // Get cache duration from deployment config
519 + // Honour the stored cache_duration setting. It is exposed in
520 + // get_settings_schema() (min 300 / max 86400), validated, persisted
521 + // and surfaced through both abilities — but the cache manager was
522 + // always built from the hardcoded config value, so the setting had
523 + // no effect (#473). Falls back to the config default.
361 524 $cache_duration = $this->deployment_config['caching']['duration'] ?? 3600;
525 +
526 + $stored = $this->get_settings('site', null)['cache_duration'] ?? null;
527 + if (is_numeric($stored) && (int) $stored > 0) {
528 + $cache_duration = (int) $stored;
529 + }
530 +
362 531 $this->cache_manager = new Schema_Cache_Manager($cache_duration);
363 532 }
364 533 }
365 534
@@ -367,12 +536,19 @@
367 536 * Generate schema markup with comprehensive content analysis integration
368 537 *
369 538 * @since 1.0.0
370 539 *
540 + * Generation is read-only by default. Persisting the result is opt-in via
541 + * `$options['persist']`, because this method is also reached from the
542 + * front-end read path (get_output_data()) and from GET routes — where a
543 + * DELETE + INSERT would destroy the admin's deployed rows and publish
544 + * types nobody deployed (#460).
545 + *
371 546 * @param string $context_type Context type
372 547 * @param int|null $context_id Context ID
373 548 * @param array $schema_types Schema types to generate
374 - * @param array $options Generation options
549 + * @param array $options Generation options. Pass `persist => true`
550 + * from explicit write paths only.
375 551 * @return array Comprehensive schema generation results
376 552 */
377 553 public function generate_schema_markup(string $context_type, ?int $context_id, array $schema_types = [], array $options = []): array {
378 554 $generation = [
@@ -443,10 +619,16 @@
443 619
444 620 // Check deployment readiness
445 621 $generation['deployment_ready'] = $this->check_deployment_readiness($generation['validation_results']);
446 622
447 - // Store schema data
448 - $this->store_schema_data($context_type, $context_id, $generation);
623 + // Persistence belongs to deployment, not generation. Every write path
624 + // (refresh_schema_for_foreign_settings(), auto_deploy_schema_on_settings_change(),
625 + // the deploy route) calls deploy_schema_markup() straight after generating,
626 + // so nothing needs to opt in today — the flag exists to keep this an
627 + // explicit decision rather than an accident.
628 + if (!empty($options['persist'])) {
629 + $this->store_schema_data($context_type, $context_id, $generation);
630 + }
449 631
450 632 return $generation;
451 633 }
452 634
@@ -574,8 +756,24 @@
574 756
575 757 // Determine deployment method
576 758 $deployment['deployment_method'] = $this->determine_deployment_method($options);
577 759
760 + // When the caller owns the whole context — the user pressing Deploy, where
761 + // the payload is exactly what the preview showed — anything not in that
762 + // payload should come off the page (#464). Incremental callers such as
763 + // auto_deploy_schema_on_settings_change() pass only the types they
764 + // regenerated, so they must NOT retire the rest.
765 + if (!empty($options['authoritative'])) {
766 + $deployment['retired_schemas'] = $this->retire_schema_types(
767 + $context_type,
768 + $context_id,
769 + array_diff(
770 + array_keys($this->get_deployed_schemas($context_type, $context_id)),
771 + array_keys($schema_data)
772 + )
773 + );
774 + }
775 +
578 776 // Deploy each schema
579 777 foreach ($schema_data as $schema_type => $schema) {
580 778 $deploy_result = $this->deploy_single_schema($schema, $schema_type, $deployment['deployment_method'], $context_type, $context_id);
581 779 $deployment['deployed_schemas'][$schema_type] = $deploy_result;
@@ -661,9 +859,9 @@
661 859 }
662 860
663 861 return [
664 862 'validation_passed' => true,
665 - 'message' => __('Schema deployed and verified on the front end', 'thinkrank'),
863 + 'message' => __('Schema deployed and read back from storage', 'thinkrank'),
666 864 'missing_types' => []
667 865 ];
668 866 }
669 867
@@ -783,9 +981,11 @@
783 981 'validation_results' => [],
784 982 'rich_snippets_preview' => [],
785 983 'performance_data' => [],
786 984 'recommendations' => [],
787 - 'enabled' => true
985 + // Report the real setting. Hardcoding true here told every consumer
986 + // the feature was on even when the master switch was off (#461).
987 + 'enabled' => (bool) ($settings['enabled'] ?? true)
788 988 ];
789 989
790 990 // Get enabled schema types
791 991 $enabled_types = $settings['enabled_schema_types'] ?? [];
@@ -1171,38 +1371,59 @@
1171 1371 if ($this->has_person_settings_changed($settings)) {
1172 1372 $schema_types_to_regenerate[] = 'Person';
1173 1373 }
1174 1374
1375 + // Honour the user's Schema Types selection. Without this the payload
1376 + // shape alone decided what shipped, so every save deployed all four
1377 + // types — including ones the user had explicitly deselected (#461).
1378 + // An empty selection means "auto", so only filter when one is set.
1379 + $enabled_types = $settings['enabled_schema_types'] ?? $this->get_settings($context_type, $context_id)['enabled_schema_types'] ?? [];
1380 +
1381 + if (!empty($enabled_types) && is_array($enabled_types)) {
1382 + $schema_types_to_regenerate = array_values(
1383 + array_intersect($schema_types_to_regenerate, $enabled_types)
1384 + );
1385 + }
1386 +
1387 + // Types that were deployed but are no longer wanted must come back off
1388 + // the page — deployment used to be additive-only (#464).
1389 + $this->retire_unselected_schema_types($context_type, $context_id, $enabled_types);
1390 +
1175 1391 // If no schema types need regeneration, return early
1176 1392 if (empty($schema_types_to_regenerate)) {
1177 1393 return;
1178 1394 }
1179 1395
1180 - // Generate and deploy each schema type
1181 - foreach ($schema_types_to_regenerate as $schema_type) {
1182 - try {
1183 - // Generate schema using generate_schema_markup
1184 - $generation_result = $this->generate_schema_markup(
1185 - $context_type,
1186 - $context_id,
1187 - [$schema_type]
1188 - );
1396 + // Generate every affected type in ONE call. Generating them one at a
1397 + // time re-entered store_schema_data() per type, and each pass replaced
1398 + // the rows written by the previous one, so only the last type survived
1399 + // (#454). One batch also means one delete and one cache flush.
1400 + try {
1401 + $generation_result = $this->generate_schema_markup(
1402 + $context_type,
1403 + $context_id,
1404 + $schema_types_to_regenerate
1405 + );
1189 1406
1190 - // Deploy if generation was successful
1191 - if (!empty($generation_result['generated_schemas'][$schema_type]) && $generation_result['deployment_ready']) {
1192 - $this->deploy_schema_markup(
1193 - $context_type,
1194 - $context_id,
1195 - [$schema_type => $generation_result['generated_schemas'][$schema_type]]
1196 - );
1407 + $deployable = [];
1408 + foreach ($schema_types_to_regenerate as $schema_type) {
1409 + // Only deploy what validated — see #470.
1410 + if (!empty($generation_result['generated_schemas'][$schema_type])
1411 + && !empty($generation_result['validation_results'][$schema_type]['is_valid'])
1412 + ) {
1413 + $deployable[$schema_type] = $generation_result['generated_schemas'][$schema_type];
1197 1414 }
1198 - } catch (\Exception $e) {
1199 - // Log error but don't fail the settings save
1200 - if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
1201 - // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
1202 - error_log('ThinkRank: Auto-deploy failed for ' . $schema_type . ': ' . $e->getMessage());
1203 - }
1204 1415 }
1416 +
1417 + if (!empty($deployable)) {
1418 + $this->deploy_schema_markup($context_type, $context_id, $deployable);
1419 + }
1420 + } catch (\Exception $e) {
1421 + // Log error but don't fail the settings save
1422 + if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
1423 + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
1424 + error_log('ThinkRank: Auto-deploy failed for ' . implode(', ', $schema_types_to_regenerate) . ': ' . $e->getMessage());
1425 + }
1205 1426 }
1206 1427 }
1207 1428
1208 1429 /**
@@ -1240,9 +1461,15 @@
1240 1461 * @param array $settings Updated settings
1241 1462 * @return bool True if website settings changed
1242 1463 */
1243 1464 private function has_website_settings_changed(array $settings): bool {
1244 - $website_keys = ['site_name', 'site_description', 'site_url'];
1465 + // These are the keys the Website tab actually stores. It previously
1466 + // looked for site_name/site_description/site_url, which belong to Site
1467 + // Identity and never appear in a schema settings payload — so WebSite
1468 + // schema never auto-deployed no matter what was edited (#455).
1469 + $website_keys = [
1470 + 'website_name', 'website_url', 'website_description', 'website_author',
1471 + ];
1245 1472
1246 1473 foreach ($website_keys as $key) {
1247 1474 if (isset($settings[$key])) {
1248 1475 return true;
@@ -1260,11 +1487,20 @@
1260 1487 * @param array $settings Updated settings
1261 1488 * @return bool True if business settings changed
1262 1489 */
1263 1490 private function has_business_settings_changed(array $settings): bool {
1491 + // Only the keys this manager actually stores. business_name/address/
1492 + // phone/hours live in the site_identity category and never reach a
1493 + // schema settings save, so keying off them meant LocalBusiness never
1494 + // auto-deployed (#455). Edits to those fields refresh LocalBusiness
1495 + // through the Site Identity save path instead — see
1496 + // refresh_schema_for_foreign_settings().
1264 1497 $business_keys = [
1265 - 'business_name', 'business_type', 'business_address', 'business_phone',
1266 - 'business_hours', 'business_price_range'
1498 + 'enable_local_business',
1499 + 'business_price_range',
1500 + 'business_geo_latitude',
1501 + 'business_geo_longitude',
1502 + 'business_opening_hours',
1267 1503 ];
1268 1504
1269 1505 foreach ($business_keys as $key) {
1270 1506 if (isset($settings[$key])) {
@@ -1308,8 +1544,29 @@
1308 1544 $detected_types = [];
1309 1545
1310 1546 switch ($context_type) {
1311 1547 case 'site':
1548 + // The admin's Schema Types selection is the answer to "what
1549 + // does this site need"; detection is only the fallback for an
1550 + // install that has not chosen yet (#456).
1551 + $settings = $this->get_settings($context_type, $context_id);
1552 + $enabled = array_values(array_filter(
1553 + array_map('strval', (array) ($settings['enabled_schema_types'] ?? [])),
1554 + 'strlen'
1555 + ));
1556 +
1557 + // Drop stale names the factory no longer registers rather than
1558 + // handing them to the builder to silently skip.
1559 + $enabled = array_values(array_filter(
1560 + $enabled,
1561 + fn($type) => isset($this->schema_types[$type])
1562 + ));
1563 +
1564 + if (!empty($enabled)) {
1565 + $detected_types = $enabled;
1566 + break;
1567 + }
1568 +
1312 1569 $detected_types = ['Organization'];
1313 1570 // Check if it's a local business
1314 1571 if ($this->is_local_business()) {
1315 1572 $detected_types[] = 'LocalBusiness';
@@ -1375,16 +1632,20 @@
1375 1632 if ($post) {
1376 1633 $content_data = [
1377 1634 'title' => $post->post_title,
1378 1635 'url' => get_permalink($post->ID),
1379 - 'excerpt' => $post->post_excerpt ?: wp_trim_words($post->post_content, 30),
1636 + 'excerpt' => $post->post_excerpt ?: \ThinkRank\Core\Seo_Text::trim_words($post->post_content, 30),
1380 1637 'content' => $post->post_content,
1381 1638 'author' => [
1382 1639 'name' => get_the_author_meta('display_name', $post->post_author),
1383 1640 'url' => get_author_posts_url($post->post_author)
1384 1641 ],
1385 - 'date' => $post->post_date,
1386 - 'modified' => $post->post_modified,
1642 + // ISO 8601 with offset. post_date/post_modified are raw
1643 + // MySQL columns in site-local time with no timezone, which
1644 + // Google rejects as "Invalid value in field datePublished"
1645 + // and drops the Article rich result (#465).
1646 + 'date' => get_the_date('c', $post),
1647 + 'modified' => get_the_modified_date('c', $post),
1387 1648 'image' => get_the_post_thumbnail_url($post->ID, 'full'),
1388 1649 'focus_keywords' => Focus_Keywords::get($post->ID),
1389 1650 'business_data' => $this->get_business_data_from_local_seo(),
1390 1651 'site_data' => $this->get_site_data_for_schema(),
@@ -1479,10 +1740,16 @@
1479 1740 global $wpdb;
1480 1741
1481 1742 $table_name = $wpdb->prefix . 'thinkrank_seo_schema';
1482 1743
1483 - // First, delete all existing schemas for this context to ensure clean storage
1484 - $this->delete_existing_schemas($context_type, $context_id);
1744 + // Replace only the types in this batch. Clearing the whole context
1745 + // destroyed types the caller never asked about — and callers do
1746 + // regenerate a subset, one type at a time (#454).
1747 + $generated_types = array_keys($generation['generated_schemas'] ?? []);
1748 + if (empty($generated_types)) {
1749 + return false;
1750 + }
1751 + $this->delete_existing_schemas($context_type, $context_id, $generated_types);
1485 1752
1486 1753 foreach ($generation['generated_schemas'] as $schema_type => $schema_data) {
1487 1754 // Prepare schema data with validation status embedded
1488 1755 $schema_data_with_validation = $schema_data;
@@ -1498,9 +1765,13 @@
1498 1765 'context_id' => $context_id,
1499 1766 'schema_type' => $schema_type,
1500 1767 'schema_data' => wp_json_encode($schema_data_with_validation),
1501 1768 'validation_status' => $generation['validation_results'][$schema_type]['is_valid'] ? 'valid' : 'invalid',
1502 - 'is_active' => $generation['deployment_ready'] ? 1 : 0
1769 + // Per-type, not batch-wide. deployment_ready is only true when
1770 + // EVERY type in the batch validated, so one invalid type (a site
1771 + // with no Business Info makes LocalBusiness invalid) deactivated
1772 + // all the valid ones alongside it (#470).
1773 + 'is_active' => !empty($generation['validation_results'][$schema_type]['is_valid']) ? 1 : 0
1503 1774 ];
1504 1775
1505 1776 // Insert new schema (existing ones were already deleted)
1506 1777 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Schema insertion requires direct database access
@@ -1850,8 +2121,26 @@
1850 2121 if (isset($schema_data['_validation'])) {
1851 2122 unset($schema_data['_validation']);
1852 2123 }
1853 2124
2125 + // Deployed schema is a snapshot, so rows written before #465
2126 + // still carry raw MySQL datetimes. Normalise on read so the
2127 + // fix reaches existing sites without a migration.
2128 + $schema_data = $this->normalize_stored_schema($schema_data);
2129 +
2130 + // The permalink was frozen at deploy time, so schema deployed
2131 + // while a post was a draft advertised "?p=123" as both url and
2132 + // mainEntityOfPage forever — contradicting the node's own @id
2133 + // and the canonical (#470). Resolve it live instead.
2134 + $schema_data = $this->refresh_schema_permalink($schema_data, $context_type, $context_id);
2135 +
2136 + // schema.org types `sameAs`, `url`, `logo` and `image` as URLs,
2137 + // but the form stored whatever was typed, so free text entered
2138 + // in a social-profile field shipped as a sameAs member and made
2139 + // the whole entity invalid (#480). Drop bad values on read, so
2140 + // existing sites stop emitting them without a migration.
2141 + $schema_data = $this->filter_entity_urls($schema_data);
2142 +
1854 2143 $processed_schemas[$schema_type] = [
1855 2144 'data' => $schema_data,
1856 2145 'method' => 'json_ld', // Default method
1857 2146 'type' => $schema_type
@@ -1871,8 +2160,233 @@
1871 2160 return $processed_schemas;
1872 2161 }
1873 2162
1874 2163 /**
2164 + * Properties schema.org defines as URLs.
2165 + *
2166 + * @since 2.0.2
2167 + * @var string[]
2168 + */
2169 + private const URL_PROPERTIES = ['sameAs', 'url', 'logo', 'image'];
2170 +
2171 + /**
2172 + * Whether a value is a URL safe to publish in structured data.
2173 + *
2174 + * @since 2.0.2
2175 + *
2176 + * @param mixed $url Candidate value.
2177 + * @return bool
2178 + */
2179 + private function is_publishable_url($url): bool {
2180 + if (!is_string($url) || '' === trim($url)) {
2181 + return false;
2182 + }
2183 +
2184 + if (!filter_var($url, FILTER_VALIDATE_URL)) {
2185 + return false;
2186 + }
2187 +
2188 + $scheme = wp_parse_url($url, PHP_URL_SCHEME);
2189 +
2190 + return in_array(strtolower((string) $scheme), ['http', 'https'], true);
2191 + }
2192 +
2193 + /**
2194 + * Drop values that are not URLs from URL-typed properties.
2195 + *
2196 + * An absent property is valid; one holding free text is not, and it can
2197 + * invalidate the entity around it. Nested objects (`logo` and `image` are
2198 + * frequently ImageObjects) are walked so a bad `url` inside one is caught
2199 + * too. A property left with nothing is removed rather than emitted empty.
2200 + *
2201 + * @since 2.0.2
2202 + *
2203 + * @param array $schema Decoded schema data.
2204 + * @return array Schema carrying only publishable URLs.
2205 + */
2206 + private function filter_entity_urls(array $schema): array {
2207 + foreach ($schema as $key => $value) {
2208 + if (is_array($value) && !in_array($key, self::URL_PROPERTIES, true)) {
2209 + $schema[$key] = $this->filter_entity_urls($value);
2210 + continue;
2211 + }
2212 +
2213 + if (!in_array($key, self::URL_PROPERTIES, true)) {
2214 + continue;
2215 + }
2216 +
2217 + // A nested object (ImageObject and friends) carries its own url.
2218 + if (is_array($value) && isset($value['@type'])) {
2219 + $schema[$key] = $this->filter_entity_urls($value);
2220 + continue;
2221 + }
2222 +
2223 + if (is_array($value)) {
2224 + $kept = [];
2225 +
2226 + foreach ($value as $item) {
2227 + if (is_array($item)) {
2228 + $kept[] = $this->filter_entity_urls($item);
2229 + } elseif ($this->is_publishable_url($item)) {
2230 + $kept[] = $item;
2231 + }
2232 + }
2233 +
2234 + if ([] === $kept) {
2235 + unset($schema[$key]);
2236 + } else {
2237 + $schema[$key] = array_values($kept);
2238 + }
2239 +
2240 + continue;
2241 + }
2242 +
2243 + if (!$this->is_publishable_url($value)) {
2244 + unset($schema[$key]);
2245 + }
2246 + }
2247 +
2248 + return $schema;
2249 + }
2250 +
2251 + /**
2252 + * Schema types whose `url` identifies the entity, not the page.
2253 + *
2254 + * On a Person or an Organization, `url` is that entity's own website, so
2255 + * overwriting it with the permalink of whichever post the schema happens to
2256 + * be deployed on is simply wrong. It also breaks graph assembly: the site
2257 + * identity emits the same entity with its real `url`, and once the two
2258 + * copies disagree they can no longer be recognised as one entity (#479).
2259 + *
2260 + * @since 2.0.2
2261 + * @var string[]
2262 + */
2263 + private const ENTITY_URL_TYPES = ['Person', 'Organization', 'LocalBusiness'];
2264 +
2265 + /**
2266 + * Replace a stored permalink snapshot with the post's live permalink.
2267 + *
2268 + * Only touches `url` and `mainEntityOfPage`, and only for post-like
2269 + * contexts where a permalink actually exists. Identity entities are
2270 + * exempt from the `url` rewrite — see self::ENTITY_URL_TYPES.
2271 + *
2272 + * @since 1.16.0
2273 + *
2274 + * @param array $schema Decoded schema data.
2275 + * @param string $context_type Context type.
2276 + * @param int|null $context_id Context ID.
2277 + * @return array Schema with a current permalink.
2278 + */
2279 + private function refresh_schema_permalink(array $schema, string $context_type, ?int $context_id): array {
2280 + if ('site' === $context_type || empty($context_id)) {
2281 + return $schema;
2282 + }
2283 +
2284 + $permalink = get_permalink($context_id);
2285 +
2286 + if (!$permalink) {
2287 + return $schema;
2288 + }
2289 +
2290 + $type = $schema['@type'] ?? '';
2291 + $type = is_array($type) ? reset($type) : $type;
2292 + // A LocalBusiness is deployed under the subtype the site chose, so the
2293 + // exemption has to cover every subtype, not only the literal root.
2294 + $is_entity = in_array((string) $type, self::ENTITY_URL_TYPES, true)
2295 + || \ThinkRank\Config\Local_Business_Types_Config::is_local_business($type);
2296 +
2297 + if (isset($schema['url']) && !$is_entity) {
2298 + $schema['url'] = $permalink;
2299 + }
2300 +
2301 + if (isset($schema['mainEntityOfPage'])) {
2302 + if (is_array($schema['mainEntityOfPage'])) {
2303 + if (isset($schema['mainEntityOfPage']['@id'])) {
2304 + $schema['mainEntityOfPage']['@id'] = $permalink;
2305 + }
2306 + } else {
2307 + $schema['mainEntityOfPage'] = $permalink;
2308 + }
2309 + }
2310 +
2311 + return $schema;
2312 + }
2313 +
2314 + /**
2315 + * Normalise properties that stored snapshots may hold in a stale format.
2316 + *
2317 + * Deployed schema is written once and read forever, so a formatting fix in
2318 + * the builder never reaches rows already on disk. Correcting on read means
2319 + * existing sites benefit without a migration.
2320 + *
2321 + * Covers non-ISO-8601 dates (#465) and WP locales in inLanguage, which must
2322 + * be a BCP-47 tag — en-US, not en_US (#473). Walks nested nodes so values
2323 + * inside author/publisher/@graph entries are covered too.
2324 + *
2325 + * Also decodes HTML entities in plain-text properties. Schema_Builder
2326 + * stored the block editor's `&` as-is until 2.10.0, and nothing
2327 + * decodes JSON-LD downstream, so every deployed node built from post text
2328 + * published the entity literally.
2329 + *
2330 + * @since 1.16.0
2331 + * @since 2.10.0 Decodes entities in plain-text properties.
2332 + *
2333 + * @param array $schema Decoded schema data.
2334 + * @return array Normalised schema.
2335 + */
2336 + private function normalize_stored_schema(array $schema): array {
2337 + static $date_keys = [
2338 + 'datePublished', 'dateModified', 'dateCreated', 'uploadDate',
2339 + 'startDate', 'endDate', 'validFrom', 'validThrough', 'expires',
2340 + ];
2341 +
2342 + // Plain text in schema.org. Answer/HowToStep `text` is deliberately
2343 + // absent: Google reads Answer.text as HTML, where an entity is correct
2344 + // and decoding `<` would turn escaped text into live markup.
2345 + static $text_keys = [
2346 + 'name', 'headline', 'alternativeHeadline', 'description',
2347 + 'reviewBody', 'about', 'abstract', 'caption',
2348 + ];
2349 +
2350 + foreach ($schema as $key => $value) {
2351 + if (is_array($value)) {
2352 + $schema[$key] = $this->normalize_stored_schema($value);
2353 + continue;
2354 + }
2355 +
2356 + if ('inLanguage' === $key && is_string($value) && '' !== $value) {
2357 + $schema[$key] = str_replace('_', '-', $value);
2358 + continue;
2359 + }
2360 +
2361 + // Decode only: a snapshot already truncated with an ellipsis must
2362 + // keep it, which the full Seo_Text::normalize_schema_text() would
2363 + // strip as an excerpt marker.
2364 + if (in_array($key, $text_keys, true) && is_string($value) && '' !== $value) {
2365 + $schema[$key] = \ThinkRank\Core\Seo_Text::decode_schema_entities($value);
2366 + continue;
2367 + }
2368 +
2369 + if (!in_array($key, $date_keys, true) || !is_string($value) || '' === $value) {
2370 + continue;
2371 + }
2372 +
2373 + // Already ISO 8601 — leave it alone.
2374 + if (preg_match('/^\d{4}-\d{2}-\d{2}T/', $value)) {
2375 + continue;
2376 + }
2377 +
2378 + $timestamp = strtotime($value);
2379 +
2380 + if (false !== $timestamp) {
2381 + $schema[$key] = (string) wp_date('c', $timestamp);
2382 + }
2383 + }
2384 +
2385 + return $schema;
2386 + }
2387 +
2388 + /**
1875 2389 * Clean up duplicate schemas in database
1876 2390 *
1877 2391 * @since 1.0.0
1878 2392 *
@@ -1924,28 +2438,131 @@
1924 2438 }
1925 2439
1926 2440 return $deleted ?: 0;
1927 2441 }
2442 +
1928 2443 /**
1929 - * Delete all existing schemas for a context before storing new ones
2444 + * Deactivate deployed schema rows for the given types.
1930 2445 *
2446 + * Deployment was insert-only, so anything ever deployed to a context stayed
2447 + * on the page forever — switching a post's schema type left the old one live
2448 + * and deactivating a saved schema did nothing (#464). Rows are deactivated
2449 + * rather than deleted so a later redeploy can revive them and so there is a
2450 + * trail of what was published.
2451 + *
2452 + * @since 1.16.0
2453 + *
2454 + * @param string $context_type Context type.
2455 + * @param int|null $context_id Context ID.
2456 + * @param string[] $schema_types Types to retire.
2457 + * @return int Number of rows deactivated.
2458 + */
2459 + private function retire_schema_types(string $context_type, ?int $context_id, array $schema_types): int {
2460 + $schema_types = array_values(array_filter(array_map('strval', $schema_types), 'strlen'));
2461 +
2462 + if (empty($schema_types)) {
2463 + return 0;
2464 + }
2465 +
2466 + global $wpdb;
2467 +
2468 + $table_name = $wpdb->prefix . 'thinkrank_seo_schema';
2469 + $placeholders = implode(', ', array_fill(0, count($schema_types), '%s'));
2470 +
2471 + if (null === $context_id) {
2472 + $sql = sprintf(
2473 + 'UPDATE %s SET is_active = 0 WHERE context_type = %%s AND context_id IS NULL AND schema_type IN (%s)',
2474 + $table_name,
2475 + $placeholders
2476 + );
2477 + $args = array_merge([$context_type], $schema_types);
2478 + } else {
2479 + $sql = sprintf(
2480 + 'UPDATE %s SET is_active = 0 WHERE context_type = %%s AND context_id = %%d AND schema_type IN (%s)',
2481 + $table_name,
2482 + $placeholders
2483 + );
2484 + $args = array_merge([$context_type, $context_id], $schema_types);
2485 + }
2486 +
2487 + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Retiring deployed schema rows requires direct database access.
2488 + $updated = $wpdb->query(
2489 + $wpdb->prepare(
2490 + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- SQL is built from an internal table name and generated placeholders.
2491 + $sql,
2492 + $args
2493 + )
2494 + );
2495 +
2496 + if ($updated && $this->cache_manager) {
2497 + $this->cache_manager->invalidate_context_cache($context_type, $context_id);
2498 + }
2499 +
2500 + return (int) ($updated ?: 0);
2501 + }
2502 +
2503 + /**
2504 + * Retire deployed types that are no longer in the user's Schema Types selection.
2505 + *
2506 + * An empty selection means "auto-detect", so nothing is retired in that case.
2507 + *
2508 + * @since 1.16.0
2509 + *
2510 + * @param string $context_type Context type.
2511 + * @param int|null $context_id Context ID.
2512 + * @param array $enabled_types The user's selected types.
2513 + * @return int Number of rows deactivated.
2514 + */
2515 + private function retire_unselected_schema_types(string $context_type, ?int $context_id, array $enabled_types): int {
2516 + if (empty($enabled_types)) {
2517 + return 0;
2518 + }
2519 +
2520 + $deployed = array_keys($this->get_deployed_schemas($context_type, $context_id));
2521 + $stale = array_diff($deployed, $enabled_types);
2522 +
2523 + return $this->retire_schema_types($context_type, $context_id, $stale);
2524 + }
2525 +
2526 + /**
2527 + * Delete stored schemas for a context before storing new ones.
2528 + *
2529 + * `$schema_types` scopes the delete to the types actually being rewritten.
2530 + * Without it this wiped every type in the context, which silently destroyed
2531 + * deployed schema whenever a caller regenerated a subset — and
2532 + * auto_deploy_schema_on_settings_change() regenerates one type at a time
2533 + * (#454). Passing an empty array keeps the original clear-the-context
2534 + * behaviour for callers that genuinely rewrite everything.
2535 + *
1931 2536 * @since 1.0.0
1932 2537 *
1933 2538 * @param string $context_type Context type
1934 2539 * @param int|null $context_id Context ID
2540 + * @param string[] $schema_types Optional. Limit the delete to these types.
1935 2541 * @return int Number of schemas deleted
1936 2542 */
1937 - private function delete_existing_schemas(string $context_type, ?int $context_id): int {
2543 + private function delete_existing_schemas(string $context_type, ?int $context_id, array $schema_types = []): int {
1938 2544 global $wpdb;
1939 2545
1940 2546 $table_name = $wpdb->prefix . 'thinkrank_seo_schema';
1941 2547
2548 + // Build an optional `AND schema_type IN (…)` clause with one prepared
2549 + // placeholder per type, so the scoping cannot be injected through.
2550 + $type_clause = '';
2551 + $type_values = [];
2552 + $schema_types = array_values(array_filter(array_map('strval', $schema_types), 'strlen'));
2553 + if (!empty($schema_types)) {
2554 + $type_clause = ' AND schema_type IN (' . implode(', ', array_fill(0, count($schema_types), '%s')) . ')';
2555 + $type_values = $schema_types;
2556 + }
2557 +
1942 2558 if (null === $context_id) {
1943 2559 // Delete all schemas for NULL context_id
1944 2560 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Schema deletion requires direct database access
1945 2561 $sql = sprintf(
1946 - 'DELETE FROM %s WHERE context_type = %%s AND context_id IS NULL',
1947 - $table_name
2562 + 'DELETE FROM %s WHERE context_type = %%s AND context_id IS NULL%s',
2563 + $table_name,
2564 + $type_clause
1948 2565 );
1949 2566 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Schema deletion requires direct database access
1950 2567 $deleted = $wpdb->query(
1951 2568 $wpdb->prepare(
@@ -1950,9 +2567,9 @@
1950 2567 $deleted = $wpdb->query(
1951 2568 $wpdb->prepare(
1952 2569 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- SQL is properly prepared with placeholders
1953 2570 $sql,
1954 - $context_type
2571 + array_merge([$context_type], $type_values)
1955 2572 )
1956 2573 );
1957 2574 } else {
1958 2575 // Delete all schemas for specific context_id
@@ -1957,10 +2574,11 @@
1957 2574 } else {
1958 2575 // Delete all schemas for specific context_id
1959 2576 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Schema deletion requires direct database access
1960 2577 $sql = sprintf(
1961 - 'DELETE FROM %s WHERE context_type = %%s AND context_id = %%d',
1962 - $table_name
2578 + 'DELETE FROM %s WHERE context_type = %%s AND context_id = %%d%s',
2579 + $table_name,
2580 + $type_clause
1963 2581 );
1964 2582 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Schema deletion requires direct database access
1965 2583 $deleted = $wpdb->query(
1966 2584 $wpdb->prepare(
@@ -1965,10 +2583,9 @@
1965 2583 $deleted = $wpdb->query(
1966 2584 $wpdb->prepare(
1967 2585 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- SQL is properly prepared with placeholders
1968 2586 $sql,
1969 - $context_type,
1970 - $context_id
2587 + array_merge([$context_type, $context_id], $type_values)
1971 2588 )
1972 2589 );
1973 2590 }
1974 2591
@@ -2052,8 +2669,11 @@
2052 2669 'site_url' => home_url(),
2053 2670 'admin_email' => get_option('admin_email'),
2054 2671 'language' => get_locale(),
2055 2672 'timezone' => get_option('timezone_string'),
2673 + // Read by populate_website_schema(), so the deployed WebSite node
2674 + // carries the same alternateName as the default one (#692).
2675 + 'alternate_name' => $site_identity_settings['alternate_name'] ?? '',
2056 2676 'founded_date' => $site_identity_settings['founded_date'] ?? '',
2057 2677 'founder_name' => $site_identity_settings['founder_name'] ?? '',
2058 2678 'company_type' => $site_identity_settings['company_type'] ?? 'Organization',
2059 2679 // Site Identity assets