This commit is contained in:
2026-07-02 15:54:39 -06:00
commit 9883323161
17470 changed files with 4470592 additions and 0 deletions
@@ -0,0 +1,65 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.3.1] - 2026-06-29
### Changed
- Update package dependencies. [#49271]
## [0.3.0] - 2026-06-25
### Added
- Expose `seo.surface_visible` on the admin script data so the legacy Traffic page can hide its SEO/Sitemaps sections for sites on the new SEO experience. [#49697]
### Changed
- Gate the Settings, Content, and AI tabs behind the enable-SEO-tools card when the SEO Tools module is off. [#49844]
- Improve contrast on the SEO admin pages so content cards and the social link preview stand out. [#49874]
- Show completion rings for all four Content SEO settings instead of only schema and meta description. [#49847]
- Simplify the search/social preview cards on the SEO Settings tab. [#49846]
- Use explicit Save buttons for the SEO Settings text-heavy sections instead of auto-saving on blur. [#49845]
### Fixed
- Fix a `@wordpress/ui` 0.15 type error in the title-structure field. [#49800]
- Keep the SEO dashboard tab strip pinned while scrolling. [#49874]
- Lay out the Content SEO coverage rings in a responsive grid. [#49865]
- SEO Settings: Add a "View sitemap" link once the sitemap is generated, and disable the sitemap toggle while search engines are blocked. [#49799]
- Stop shipping megabytes of unminified JS as part of the package. [#49699]
## [0.2.0] - 2026-06-22
### Added
- Add a Canonical URLs toggle to the Settings tab that adds `rel="canonical"` tags to archive pages. [#49463]
- Add a Content tab for editing per-post SEO with a live SERP preview, Content SEO coverage card to the Overview, and front-end JSON-LD schema for articles and FAQs. [#49351]
- Add an AI tab to the SEO dashboard and move the AI SEO Enhancer toggle onto it. [#49408]
- Add Google site auto-verification to the Settings tab, with manual meta-tag entry as a fallback. [#49412]
- Show the SEO admin menu automatically on WordPress.com and fresh installs; existing installs can opt in, and the menu stays available even when the SEO Tools module is off. [#49672]
- Add a search & social previews card to the Settings tab, previewing the home page in Google results and when shared on Facebook and X. [#49592]
- Customize the title structure for all page types from the Settings tab, not just posts. [#49587]
### Changed
- Read the canonical-URLs enabled state from the durable `jetpack_seo_canonical_urls_enabled` option (falling back to the live module state when unset). [#49407]
- Read the sitemap enabled state from the durable `jetpack_seo_sitemap_enabled` option (falling back to the live module state when unset). [#49407]
- Split the SEO dashboard into per-route wp-build stages (Overview, Settings, AI) with route-based navigation. [#49628]
- Update package dependencies. [#49631] [#49691] [#49757]
### Fixed
- Persist Settings and AI tab values across tab navigation, so a saved change shows when you return to the tab without a page reload. [#49351]
## [0.1.1] - 2026-06-15
### Changed
- Update package dependencies. [#49273]
### Fixed
- Remove the package's duplicate snackbar list. [#49470]
## 0.1.0 - 2026-06-08
### Added
- Create an Overview screen with a Site visibility card. [#49203]
- Create a Settings screen with site visibility, post title structure, front-page description, and site verification. [#49256]
- Scaffold the new `jetpack-seo` package and mount its admin page. [#49203]
[0.3.1]: https://github.com/Automattic/jetpack-seo/compare/0.3.0...0.3.1
[0.3.0]: https://github.com/Automattic/jetpack-seo/compare/0.2.0...0.3.0
[0.2.0]: https://github.com/Automattic/jetpack-seo/compare/0.1.1...0.2.0
[0.1.1]: https://github.com/Automattic/jetpack-seo/compare/0.1.0...0.1.1
@@ -0,0 +1,43 @@
<?php
/**
* Main entry point for auto-generated asset registration.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
// Load script module registration.
$modules_file = __DIR__ . '/modules.php';
if ( file_exists( $modules_file ) ) {
require_once $modules_file;
}
// Load script registration.
$scripts_file = __DIR__ . '/scripts.php';
if ( file_exists( $scripts_file ) ) {
require_once $scripts_file;
}
// Load style registration.
$styles_file = __DIR__ . '/styles.php';
if ( file_exists( $styles_file ) ) {
require_once $styles_file;
}
// Load routes registration.
$routes_file = __DIR__ . '/routes.php';
if ( file_exists( $routes_file ) ) {
require_once $routes_file;
}
// Load widgets registration.
$widgets_file = __DIR__ . '/widgets.php';
if ( file_exists( $widgets_file ) ) {
require_once $widgets_file;
}
// Load pages registration.
$pages_file = __DIR__ . '/pages.php';
if ( file_exists( $pages_file ) ) {
require_once $pages_file;
}
@@ -0,0 +1,14 @@
<?php
/**
* Plugin constants - Auto-generated by build process.
* Do not edit this file manually.
*
* Returns an array of constants for use in other templates.
*
* @package jetpack_seo
*/
return array(
'version' => '0.3.1',
'build_url' => plugin_dir_url( __FILE__ ),
);
@@ -0,0 +1,63 @@
<?php
/**
* Script module registration - Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
/**
* Register all script modules.
*/
function jetpack_seo_register_script_modules() {
// Ensure this only runs once. wp_default_scripts can fire multiple times,
// and each wp_deregister_script_module() call also dequeues the module.
// If a module was enqueued between calls, repeated deregister/register
// cycles would lose the enqueue state.
static $already_registered = false;
if ( $already_registered ) {
return;
}
$already_registered = true;
// Load build constants
$constants_file = __DIR__ . '/constants.php';
if ( ! file_exists( $constants_file ) ) {
return;
}
$build_constants = require $constants_file;
$modules_dir = __DIR__ . '/modules';
$modules_file = $modules_dir . '/registry.php';
if ( ! file_exists( $modules_file ) ) {
return;
}
$modules = require $modules_file;
$base_url = $build_constants['build_url'] . 'modules/';
foreach ( $modules as $module ) {
// WASM-only modules (e.g., vips worker) only have .min.js; use it even when SCRIPT_DEBUG is `true`.
$extension = '.min.js';
$asset_path = $modules_dir . '/' . $module['asset'];
$asset = file_exists( $asset_path ) ? require $asset_path : array();
// Deregister first to override any previously registered version
// (e.g., Core's default modules when running as a plugin).
wp_deregister_script_module( $module['id'] );
wp_register_script_module(
$module['id'],
$base_url . $module['path'] . $extension,
$asset['module_dependencies'] ?? array(),
$asset['version'] ?? false,
array(
'fetchpriority' => 'low',
'in_footer' => true,
)
);
}
}
add_action( 'wp_default_scripts', 'jetpack_seo_register_script_modules' );
@@ -0,0 +1 @@
<?php return array('dependencies' => array('react', 'react-dom', 'react-jsx-runtime', 'wp-commands', 'wp-components', 'wp-compose', 'wp-core-data', 'wp-data', 'wp-editor', 'wp-element', 'wp-html-entities', 'wp-i18n', 'wp-keyboard-shortcuts', 'wp-keycodes', 'wp-notices', 'wp-primitives', 'wp-private-apis', 'wp-theme', 'wp-url'), 'module_dependencies' => array(array('id' => '@wordpress/a11y', 'import' => 'static'), array('id' => '@wordpress/lazy-editor', 'import' => 'dynamic'), array('id' => '@wordpress/route', 'import' => 'static')), 'version' => '188faf6c64fdd1b4');
@@ -0,0 +1,11 @@
<?php
/**
* Script module registry - Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
return array(
);
@@ -0,0 +1,16 @@
<?php
/**
* Pages loader - Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
foreach ( [
__DIR__ . '/pages/jetpack-seo-dashboard/page.php',
__DIR__ . '/pages/jetpack-seo-dashboard/page-wp-admin.php',
] as $file ) {
if ( file_exists( $file ) ) {
require_once $file;
}
}
@@ -0,0 +1 @@
// Empty module loader for page dependencies
@@ -0,0 +1,317 @@
<?php
/**
* Page: jetpack-seo-dashboard (wp-admin integrated)
* Auto-generated by build process.
* Do not edit this file manually.
*
* This version integrates with the standard WordPress admin interface,
* keeping the wp-admin sidebar and scripts/styles intact.
*
* @package jetpack_seo
*/
// Global storage for jetpack-seo-dashboard routes and menu items
global $jetpack_seo_jetpack_seo_dashboard_wp_admin_routes, $jetpack_seo_jetpack_seo_dashboard_wp_admin_menu_items;
$jetpack_seo_jetpack_seo_dashboard_wp_admin_routes = array();
$jetpack_seo_jetpack_seo_dashboard_wp_admin_menu_items = array();
/**
* Register a route for the jetpack-seo-dashboard-wp-admin page.
*
* @param string $path Route path (e.g., '/types/$type/edit/$id').
* @param string|null $content_module Script module ID for content (stage/inspector).
* @param string|null $route_module Script module ID for route lifecycle hooks.
*/
function jetpack_seo_register_jetpack_seo_dashboard_wp_admin_route( $path, $content_module = null, $route_module = null ) {
global $jetpack_seo_jetpack_seo_dashboard_wp_admin_routes;
$route = array( 'path' => $path );
if ( ! empty( $content_module ) ) {
$route['content_module'] = $content_module;
}
if ( ! empty( $route_module ) ) {
$route['route_module'] = $route_module;
}
$jetpack_seo_jetpack_seo_dashboard_wp_admin_routes[] = $route;
}
/**
* Register a menu item for the jetpack-seo-dashboard-wp-admin page.
* Note: Menu items are registered but not displayed in single-page mode.
*
* @param string $id Menu item ID.
* @param string $label Display label.
* @param string $to Route path to navigate to.
* @param string $parent_id Optional. Parent menu item ID.
*/
function jetpack_seo_register_jetpack_seo_dashboard_wp_admin_menu_item( $id, $label, $to, $parent_id = '' ) {
global $jetpack_seo_jetpack_seo_dashboard_wp_admin_menu_items;
$menu_item = array(
'id' => $id,
'label' => $label,
'to' => $to,
);
if ( ! empty( $parent_id ) ) {
$menu_item['parent'] = $parent_id;
}
$jetpack_seo_jetpack_seo_dashboard_wp_admin_menu_items[] = $menu_item;
}
/**
* Get all registered routes for the jetpack-seo-dashboard-wp-admin page.
*
* @return array Array of route objects.
*/
function jetpack_seo_get_jetpack_seo_dashboard_wp_admin_routes() {
global $jetpack_seo_jetpack_seo_dashboard_wp_admin_routes;
return $jetpack_seo_jetpack_seo_dashboard_wp_admin_routes ?? array();
}
/**
* Get all registered menu items for the jetpack-seo-dashboard-wp-admin page.
*
* @return array Array of menu item objects.
*/
function jetpack_seo_get_jetpack_seo_dashboard_wp_admin_menu_items() {
global $jetpack_seo_jetpack_seo_dashboard_wp_admin_menu_items;
return $jetpack_seo_jetpack_seo_dashboard_wp_admin_menu_items ?? array();
}
/**
* Preload REST API data for the jetpack-seo-dashboard-wp-admin page.
* Automatically called during page rendering.
*/
function jetpack_seo_jetpack_seo_dashboard_wp_admin_preload_data() {
// Define paths to preload - same for all pages
// Please also change packages/core-data/src/entities.js when changing this.
$preload_paths = array(
'/?_fields=description,gmt_offset,home,image_sizes,image_size_threshold,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front',
array( '/wp/v2/settings', 'OPTIONS' ),
);
// Use rest_preload_api_request to gather the preloaded data
$preload_data = array_reduce(
$preload_paths,
'rest_preload_api_request',
array()
);
// Register the preloading middleware with wp-api-fetch
wp_add_inline_script(
'wp-api-fetch',
sprintf(
'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );',
wp_json_encode( $preload_data )
),
'after'
);
}
/**
* Enqueue scripts and styles for the jetpack-seo-dashboard-wp-admin page.
* Hooked to admin_enqueue_scripts.
*
* @param string $hook_suffix The current admin page.
*/
function jetpack_seo_jetpack_seo_dashboard_wp_admin_enqueue_scripts( $hook_suffix ) {
// Check all possible ways this page can be accessed:
// 1. Menu page via admin.php?page=jetpack-seo-dashboard-wp-admin (plugin)
// 2. Direct file via jetpack-seo-dashboard.php (Core) - screen ID will be 'jetpack-seo-dashboard'
$current_screen = get_current_screen();
$is_our_page = (
( isset( $_GET['page'] ) && 'jetpack-seo-dashboard-wp-admin' === $_GET['page'] ) || // phpcs:ignore WordPress.Security.NonceVerification.Recommended
( $current_screen && 'jetpack-seo-dashboard' === $current_screen->id )
);
if ( ! $is_our_page ) {
return;
}
// Load build constants
$build_constants = require __DIR__ . '/../../constants.php';
/**
* Fires when the jetpack-seo-dashboard admin page is initialized so extensions can register routes and menu items.
*/
do_action( 'jetpack-seo-dashboard-wp-admin_init' );
// Preload REST API data
jetpack_seo_jetpack_seo_dashboard_wp_admin_preload_data();
// Get all registered routes
$routes = jetpack_seo_get_jetpack_seo_dashboard_wp_admin_routes();
// Get boot module asset file for dependencies
$asset_file = __DIR__ . '/../../modules/boot/index.min.asset.php';
if ( file_exists( $asset_file ) ) {
$asset = require $asset_file;
// This script serves two purposes:
// 1. It ensures all the globals that are made available to the modules are loaded.
// 2. It initializes the boot module as an inline script.
wp_register_script( 'jetpack-seo-dashboard-wp-admin-prerequisites', '', $asset['dependencies'], $asset['version'], true );
/*
* Add inline script to initialize the app using initSinglePage (no menuItems).
* The dynamic import is deferred until DOMContentLoaded so that all classic
* script dependencies of @wordpress/boot (wp-private-apis, wp-components,
* wp-theme, etc.) have finished parsing and executing before the boot module
* evaluates. Otherwise, a modulepreloaded @wordpress/boot can win the race
* against the classic-script-printing pass on fast CDN-fronted hosts in
* Chrome, evaluating before wp.theme.privateApis is defined and throwing
* "Cannot unlock an undefined object". See <https://core.trac.wordpress.org/ticket/65103>.
*/
$init_js_function = <<<'JS'
( mountId, routes ) => {
const run = async () => {
const mod = await import( "@wordpress/boot" );
mod.initSinglePage( { mountId, routes } );
};
if ( document.readyState === "loading" ) {
document.addEventListener( "DOMContentLoaded", run );
} else {
run();
}
}
JS;
wp_add_inline_script(
'jetpack-seo-dashboard-wp-admin-prerequisites',
sprintf(
'( %s )( %s, %s );',
$init_js_function,
wp_json_encode( 'jetpack-seo-dashboard-wp-admin-app', JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ),
wp_json_encode( $routes, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES )
)
);
// Register prerequisites style by filtering script dependencies to find registered styles
$style_dependencies = array_filter(
$asset['dependencies'],
function ( $handle ) {
return wp_style_is( $handle, 'registered' );
}
);
wp_register_style( 'jetpack-seo-dashboard-wp-admin-prerequisites', false, $style_dependencies, $asset['version'] );
// Build dependencies for jetpack-seo-dashboard-wp-admin module
$boot_dependencies = array(
array(
'import' => 'static',
'id' => '@wordpress/boot',
),
);
// Add all registered routes as dependencies
foreach ( $routes as $route ) {
if ( isset( $route['route_module'] ) ) {
$boot_dependencies[] = array(
'import' => 'static',
'id' => $route['route_module'],
);
}
if ( isset( $route['content_module'] ) ) {
$boot_dependencies[] = array(
'import' => 'dynamic',
'id' => $route['content_module'],
);
}
}
/**
* Filters the boot script-module dependencies for the
* jetpack-seo-dashboard-wp-admin page.
*
* Surfaces extending this page can append entries to the boot
* dependency list. Each entry is an array with 'import' (string
* 'static' or 'dynamic') and 'id' (script-module handle) keys.
*
* @param array $boot_dependencies Boot dependencies for the page.
*/
$boot_dependencies = apply_filters(
'jetpack-seo-dashboard-wp-admin_boot_dependencies',
$boot_dependencies
);
// Dummy script module to ensure dependencies are loaded
wp_register_script_module(
'jetpack-seo-dashboard-wp-admin',
$build_constants['build_url'] . 'pages/jetpack-seo-dashboard/loader.js',
$boot_dependencies
);
// Enqueue the boot scripts and styles
wp_enqueue_script( 'jetpack-seo-dashboard-wp-admin-prerequisites' );
wp_enqueue_script_module( 'jetpack-seo-dashboard-wp-admin' );
wp_enqueue_style( 'jetpack-seo-dashboard-wp-admin-prerequisites' );
}
}
/**
* Render the jetpack-seo-dashboard-wp-admin page.
* Call this function from add_menu_page or add_submenu_page.
* This renders within the normal WordPress admin interface.
*/
function jetpack_seo_jetpack_seo_dashboard_wp_admin_render_page() {
?>
<style>
/* Critical styles to prevent layout shifts - inlined for immediate application */
#wpwrap {
overflow-y: auto;
}
body {
background: #fff;
}
/* Reset wp-admin padding */
#wpcontent {
padding-inline-start: 0;
}
#wpbody-content {
padding-bottom: 0;
}
/* Hide legacy admin elements */
#wpbody-content > div:not(.boot-layout-container):not(#screen-meta) {
display: none;
}
#wpfooter {
display: none;
}
/* Accessibility regions */
.a11y-speak-region {
inset-inline-start: -1px;
top: -1px;
}
/* Admin menu indicators */
ul#adminmenu a.wp-has-current-submenu::after,
ul#adminmenu > li.current > a.current::after {
border-inline-end-color: #fff;
}
/* Media frame fix */
.media-frame select.attachment-filters:last-of-type {
width: auto;
max-width: 100%;
}
/* Responsive overflow fix for #wpwrap */
@media (min-width: 782px) {
#wpwrap {
overflow-y: initial;
}
}
</style>
<div id="jetpack-seo-dashboard-wp-admin-app" class="boot-layout-container"></div>
<?php
}
// Hook the enqueue function to admin_enqueue_scripts
add_action( 'admin_enqueue_scripts', 'jetpack_seo_jetpack_seo_dashboard_wp_admin_enqueue_scripts' );
@@ -0,0 +1,318 @@
<?php
/**
* Page: jetpack-seo-dashboard
* Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
// Global storage for jetpack-seo-dashboard routes and menu items
global $jetpack_seo_jetpack_seo_dashboard_routes, $jetpack_seo_jetpack_seo_dashboard_menu_items;
$jetpack_seo_jetpack_seo_dashboard_routes = array();
$jetpack_seo_jetpack_seo_dashboard_menu_items = array();
/**
* Register a route for the jetpack-seo-dashboard page.
*
* @param string $path Route path (e.g., '/types/$type/edit/$id').
* @param string|null $content_module Script module ID for content (stage/inspector).
* @param string|null $route_module Script module ID for route lifecycle hooks.
*/
function jetpack_seo_register_jetpack_seo_dashboard_route( $path, $content_module = null, $route_module = null ) {
global $jetpack_seo_jetpack_seo_dashboard_routes;
$route = array( 'path' => $path );
if ( ! empty( $content_module ) ) {
$route['content_module'] = $content_module;
}
if ( ! empty( $route_module ) ) {
$route['route_module'] = $route_module;
}
$jetpack_seo_jetpack_seo_dashboard_routes[] = $route;
}
/**
* Register a menu item for the jetpack-seo-dashboard page.
*
* @param string $id Menu item ID.
* @param string $label Display label.
* @param string $to Route path to navigate to.
* @param string $parent_id Optional. Parent menu item ID.
* @param string $parent_type Optional. Parent type: 'drilldown' or 'dropdown'.
*/
function jetpack_seo_register_jetpack_seo_dashboard_menu_item( $id, $label, $to, $parent_id = '', $parent_type = '' ) {
global $jetpack_seo_jetpack_seo_dashboard_menu_items;
$menu_item = array(
'id' => $id,
'label' => $label,
'to' => $to,
);
if ( ! empty( $parent_id ) ) {
$menu_item['parent'] = $parent_id;
}
if ( ! empty( $parent_type ) && in_array( $parent_type, array( 'drilldown', 'dropdown' ), true ) ) {
$menu_item['parent_type'] = $parent_type;
}
$jetpack_seo_jetpack_seo_dashboard_menu_items[] = $menu_item;
}
/**
* Get all registered routes for the jetpack-seo-dashboard page.
*
* @return array Array of route objects.
*/
function jetpack_seo_get_jetpack_seo_dashboard_routes() {
global $jetpack_seo_jetpack_seo_dashboard_routes;
return $jetpack_seo_jetpack_seo_dashboard_routes ?? array();
}
/**
* Get all registered menu items for the jetpack-seo-dashboard page.
*
* @return array Array of menu item objects.
*/
function jetpack_seo_get_jetpack_seo_dashboard_menu_items() {
global $jetpack_seo_jetpack_seo_dashboard_menu_items;
return $jetpack_seo_jetpack_seo_dashboard_menu_items ?? array();
}
/**
* Preload REST API data for the jetpack-seo-dashboard page.
* Automatically called during page rendering.
*/
function jetpack_seo_jetpack_seo_dashboard_preload_data() {
// Define paths to preload - same for all pages
// Please also change packages/core-data/src/entities.js when changing this.
$preload_paths = array(
'/?_fields=description,gmt_offset,home,image_sizes,image_size_threshold,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front',
array( '/wp/v2/settings', 'OPTIONS' ),
);
// Use rest_preload_api_request to gather the preloaded data
$preload_data = array_reduce(
$preload_paths,
'rest_preload_api_request',
array()
);
// Register the preloading middleware with wp-api-fetch
wp_add_inline_script(
'wp-api-fetch',
sprintf(
'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );',
wp_json_encode( $preload_data )
),
'after'
);
}
/**
* Render the jetpack-seo-dashboard page.
* Call this function from add_menu_page or add_submenu_page.
*/
function jetpack_seo_jetpack_seo_dashboard_render_page() {
// Load build constants
$build_constants = require __DIR__ . '/../../constants.php';
// Set current screen
set_current_screen();
// Remove unwanted deprecated handler
remove_action( 'admin_head', 'wp_admin_bar_header' );
// Remove unwanted scripts and styles that were enqueued during `admin_init`
foreach ( wp_scripts()->queue as $script ) {
wp_dequeue_script( $script );
}
foreach ( wp_styles()->queue as $style ) {
wp_dequeue_style( $style );
}
/**
* Fires when the jetpack-seo-dashboard page is initialized so extensions can register routes and menu items.
*/
do_action( 'jetpack-seo-dashboard_init' );
// Enqueue command palette assets for boot-based pages
if ( function_exists( 'wp_enqueue_command_palette_assets' ) ) {
wp_enqueue_command_palette_assets();
}
// Preload REST API data
jetpack_seo_jetpack_seo_dashboard_preload_data();
// Get all registered routes and menu items
$menu_items = jetpack_seo_get_jetpack_seo_dashboard_menu_items();
$routes = jetpack_seo_get_jetpack_seo_dashboard_routes();
// Get boot module asset file for dependencies
$asset_file = __DIR__ . '/../../modules/boot/index.min.asset.php';
if ( file_exists( $asset_file ) ) {
$asset = require $asset_file;
// This script serves two purposes:
// 1. It ensures all the globals that are made available to the modules are loaded.
// 2. It initializes the boot module as an inline script.
wp_register_script( 'jetpack-seo-dashboard-prerequisites', '', $asset['dependencies'], $asset['version'], true );
// Add inline script to initialize the app
$init_modules = [];
wp_add_inline_script(
'jetpack-seo-dashboard-prerequisites',
sprintf(
'import("@wordpress/boot").then(mod => mod.init({mountId: "%s", menuItems: %s, routes: %s, initModules: %s, dashboardLink: "%s"}));',
'jetpack-seo-dashboard-app',
wp_json_encode( $menu_items, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ),
wp_json_encode( $routes, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ),
wp_json_encode( $init_modules, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ),
esc_url( admin_url( '/' ) )
)
);
// Register prerequisites style by filtering script dependencies to find registered styles
$style_dependencies = array_filter(
$asset['dependencies'],
function ( $handle ) {
return wp_style_is( $handle, 'registered' );
}
);
wp_register_style( 'jetpack-seo-dashboard-prerequisites', false, $style_dependencies, $asset['version'] );
// Build dependencies for jetpack-seo-dashboard module
$boot_dependencies = array(
array(
'import' => 'static',
'id' => '@wordpress/boot',
),
);
// Add init modules as static dependencies
// No init modules configured
// Add all registered routes as dependencies
foreach ( $routes as $route ) {
if ( isset( $route['route_module'] ) ) {
$boot_dependencies[] = array(
'import' => 'static',
'id' => $route['route_module'],
);
}
if ( isset( $route['content_module'] ) ) {
$boot_dependencies[] = array(
'import' => 'dynamic',
'id' => $route['content_module'],
);
}
}
/**
* Filters the boot script-module dependencies for the
* jetpack-seo-dashboard page.
*
* Surfaces extending this page can append entries to the boot
* dependency list. Each entry is an array with 'import' (string
* 'static' or 'dynamic') and 'id' (script-module handle) keys.
*
* @param array $boot_dependencies Boot dependencies for the page.
*/
$boot_dependencies = apply_filters(
'jetpack-seo-dashboard_boot_dependencies',
$boot_dependencies
);
// Dummy script module to ensure dependencies are loaded
wp_register_script_module(
'jetpack-seo-dashboard',
$build_constants['build_url'] . 'pages/jetpack-seo-dashboard/loader.js',
$boot_dependencies
);
// Enqueue the boot scripts and styles
wp_enqueue_script( 'jetpack-seo-dashboard-prerequisites' );
wp_enqueue_script_module( 'jetpack-seo-dashboard' );
wp_enqueue_style( 'jetpack-seo-dashboard-prerequisites' );
}
// Output the HTML
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo esc_html( get_admin_page_title() ); ?></title>
<style>
html {
background: #f1f1f1;
color: #444;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
font-size: 13px;
line-height: 1.4em;
}
body {
margin: 0;
}
#wpadminbar { display: none; }
</style>
<?php
global $hook_suffix;
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$hook_suffix = 'jetpack-seo-dashboard';
// BEGIN see wp-admin/admin-header.php
print_admin_styles();
print_head_scripts();
/** This action is documented in wp-admin/admin-header.php */
do_action( "admin_head-{$hook_suffix}" ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_head' );
// END see wp-admin/admin-header.php
?>
</head>
<body class="jetpack-seo-dashboard">
<div id="jetpack-seo-dashboard-app" style="height: 100vh; box-sizing: border-box;"></div>
<?php
// BEGIN see wp-admin/admin-footer.php
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_footer', '' );
// Print import map first so it's available for inline scripts
wp_script_modules()->print_import_map();
print_footer_scripts();
wp_script_modules()->print_enqueued_script_modules();
wp_script_modules()->print_script_module_preloads();
wp_script_modules()->print_script_module_data();
/** This action is documented in wp-admin/admin-footer.php */
do_action( "admin_footer-{$hook_suffix}" ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
// END see wp-admin/admin-footer.php
?>
</body>
</html>
<?php
exit;
}
/**
* Intercept admin_init to render the page early.
* This bypasses the default WordPress admin template.
*/
function jetpack_seo_jetpack_seo_dashboard_intercept_render() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['page'] ) && 'jetpack-seo-dashboard' === $_GET['page'] ) {
jetpack_seo_jetpack_seo_dashboard_render_page();
exit;
}
}
// Hook the interceptor to admin_init
add_action( 'admin_init', 'jetpack_seo_jetpack_seo_dashboard_intercept_render' );
@@ -0,0 +1,113 @@
<?php
/**
* Routes registration - Auto-generated by build process.
* Registers all routes on their respective page init hooks.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
// Load routes registry
$routes_file = __DIR__ . '/routes/registry.php';
if ( ! file_exists( $routes_file ) ) {
return;
}
$routes = require $routes_file;
// Group routes by page and store in globals for page-specific functions
$routes_by_page = array();
foreach ( $routes as $route ) {
$page_slug = $route['page'];
if ( ! isset( $routes_by_page[ $page_slug ] ) ) {
$routes_by_page[ $page_slug ] = array();
}
$routes_by_page[ $page_slug ][] = $route;
}
// Store routes data in globals for each page
foreach ( $routes_by_page as $page_slug => $page_routes ) {
$page_slug_underscore = str_replace( '-', '_', $page_slug );
$global_name = 'jetpack_seo_' . $page_slug_underscore . '_routes_data';
$GLOBALS[ $global_name ] = $page_routes;
}
/**
* Generic helper function to register routes for a page.
*
* @param array $page_routes Array of route data for the page.
* @param string $register_function_name Name of the function to call for registering each route.
*/
function jetpack_seo_register_page_routes( $page_routes, $register_function_name ) {
// Load build constants
$build_constants = require __DIR__ . '/constants.php';
foreach ( $page_routes as $route ) {
$content_handle = null;
$route_handle = null;
// Register content module if exists
if ( $route['has_content'] ) {
$content_asset_path = __DIR__ . "/routes/{$route['name']}/content.min.asset.php";
if ( file_exists( $content_asset_path ) ) {
$content_asset = require $content_asset_path;
$content_handle = 'jetpack-seo/routes/' . $route['name'] . '/content';
$extension = '.min.js';
// Deregister first to override any previously registered version
// (e.g., Core's default modules when running as a plugin).
wp_deregister_script_module( $content_handle );
wp_register_script_module(
$content_handle,
$build_constants['build_url'] . 'routes/' . $route['name'] . '/content' . $extension,
$content_asset['module_dependencies'] ?? array(),
$content_asset['version'] ?? false
);
}
}
// Register route module if exists
if ( $route['has_route'] ) {
$route_asset_path = __DIR__ . "/routes/{$route['name']}/route.min.asset.php";
if ( file_exists( $route_asset_path ) ) {
$route_asset = require $route_asset_path;
$route_handle = 'jetpack-seo/routes/' . $route['name'] . '/route';
$extension = '.min.js';
// Deregister first to override any previously registered version
// (e.g., Core's default modules when running as a plugin).
wp_deregister_script_module( $route_handle );
wp_register_script_module(
$route_handle,
$build_constants['build_url'] . 'routes/' . $route['name'] . '/route' . $extension,
$route_asset['module_dependencies'] ?? array(),
$route_asset['version'] ?? false
);
}
}
// Register route with page
if ( function_exists( $register_function_name ) ) {
call_user_func( $register_function_name, $route['path'], $content_handle, $route_handle );
}
}
}
// Page-specific route registration functions
// Page-specific route registration functions for jetpack-seo-dashboard
/**
* Register routes for jetpack-seo-dashboard page (full-page mode).
*/
function jetpack_seo_register_jetpack_seo_dashboard_page_routes() {
global $jetpack_seo_jetpack_seo_dashboard_routes_data;
jetpack_seo_register_page_routes( $jetpack_seo_jetpack_seo_dashboard_routes_data, 'jetpack_seo_register_jetpack_seo_dashboard_route' );
}
add_action( 'jetpack-seo-dashboard_init', 'jetpack_seo_register_jetpack_seo_dashboard_page_routes' );
/**
* Register routes for jetpack-seo-dashboard page (wp-admin mode).
*/
function jetpack_seo_register_jetpack_seo_dashboard_wp_admin_page_routes() {
global $jetpack_seo_jetpack_seo_dashboard_routes_data;
jetpack_seo_register_page_routes( $jetpack_seo_jetpack_seo_dashboard_routes_data, 'jetpack_seo_register_jetpack_seo_dashboard_wp_admin_route' );
}
add_action( 'jetpack-seo-dashboard-wp-admin_init', 'jetpack_seo_register_jetpack_seo_dashboard_wp_admin_page_routes' );
@@ -0,0 +1 @@
<?php return array('dependencies' => array('react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-compose', 'wp-data', 'wp-date', 'wp-element', 'wp-i18n', 'wp-notices', 'wp-primitives', 'wp-private-apis', 'wp-theme', 'wp-url'), 'module_dependencies' => array(array('id' => '@wordpress/a11y', 'import' => 'static'), array('id' => '@wordpress/route', 'import' => 'static')), 'version' => 'ea803cc0e156ede9a4dc');
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => 'bdca920315a6e5637299');
@@ -0,0 +1 @@
var o={};export{o as route};
@@ -0,0 +1 @@
<?php return array('dependencies' => array('react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-compose', 'wp-core-data', 'wp-data', 'wp-date', 'wp-deprecated', 'wp-element', 'wp-html-entities', 'wp-i18n', 'wp-keycodes', 'wp-notices', 'wp-primitives', 'wp-private-apis', 'wp-theme', 'wp-url', 'wp-warning'), 'module_dependencies' => array(array('id' => '@wordpress/a11y', 'import' => 'static'), array('id' => '@wordpress/route', 'import' => 'static')), 'version' => '6d9e6c0e4ca19cb050c7');
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => '35ece5d7cfedda2a0233');
@@ -0,0 +1 @@
function i(){return window.JetpackScriptData}function e(){return i()?.seo?.overview??null}function t(){return e()?.site_visibility.seo_tools_active??!1}var m={inspector:({search:r})=>t()&&!!r?.postId};export{m as route};
@@ -0,0 +1 @@
<?php return array('dependencies' => array('react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-compose', 'wp-data', 'wp-date', 'wp-element', 'wp-i18n', 'wp-notices', 'wp-primitives', 'wp-private-apis', 'wp-theme', 'wp-url'), 'module_dependencies' => array(array('id' => '@wordpress/a11y', 'import' => 'static'), array('id' => '@wordpress/route', 'import' => 'static')), 'version' => '8442dced31ce9c4f931a');
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => 'bdca920315a6e5637299');
@@ -0,0 +1 @@
var o={};export{o as route};
@@ -0,0 +1,38 @@
<?php
/**
* Route registry - Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
return array(
array(
'name' => 'ai',
'path' => '/ai',
'page' => 'jetpack-seo-dashboard',
'has_route' => true,
'has_content' => true,
),
array(
'name' => 'content',
'path' => '/content',
'page' => 'jetpack-seo-dashboard',
'has_route' => true,
'has_content' => true,
),
array(
'name' => 'overview',
'path' => '/',
'page' => 'jetpack-seo-dashboard',
'has_route' => true,
'has_content' => true,
),
array(
'name' => 'settings',
'path' => '/settings',
'page' => 'jetpack-seo-dashboard',
'has_route' => true,
'has_content' => true,
)
);
@@ -0,0 +1 @@
<?php return array('dependencies' => array('react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-compose', 'wp-data', 'wp-date', 'wp-element', 'wp-i18n', 'wp-notices', 'wp-primitives', 'wp-private-apis', 'wp-theme', 'wp-url'), 'module_dependencies' => array(array('id' => '@wordpress/a11y', 'import' => 'static'), array('id' => '@wordpress/route', 'import' => 'static')), 'version' => '1b1e1ad5ab9d229f31f7');
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => 'bdca920315a6e5637299');
@@ -0,0 +1 @@
var o={};export{o as route};
@@ -0,0 +1,85 @@
<?php
/**
* Script registration - Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
/**
* Registers a script according to `wp_register_script`. Honors this request by
* reassigning internal dependency properties of any script handle already
* registered by that name. It does not deregister the original script, to
* avoid losing inline scripts which may have been attached.
*
* @param WP_Scripts $scripts WP_Scripts instance.
* @param string $handle Name of the script. Should be unique.
* @param string $src Full URL of the script, or path of the script relative to the WordPress root directory.
* @param array $deps Optional. An array of registered script handles this script depends on. Default empty array.
* @param string|bool|null $ver Optional. String specifying script version number, if it has one, which is added to the URL
* as a query string for cache busting purposes. If version is set to false, a version
* number is automatically added equal to current installed WordPress version.
* If set to null, no version is added.
* @param bool $in_footer Optional. Whether to enqueue the script before </body> instead of in the <head>.
* Default 'false'.
*/
function jetpack_seo_override_script( $scripts, $handle, $src, $deps = array(), $ver = false, $in_footer = false ) {
$script = $scripts->query( $handle, 'registered' );
if ( $script ) {
/*
* In many ways, this is a reimplementation of `wp_register_script` but
* bypassing consideration of whether a script by the given handle had
* already been registered.
*/
// See: `_WP_Dependency::__construct` .
$script->src = $src;
$script->deps = $deps;
$script->ver = $ver;
$script->args = $in_footer ? 1 : null;
} else {
$scripts->add( $handle, $src, $deps, $ver, ( $in_footer ? 1 : null ) );
}
if ( in_array( 'wp-i18n', $deps, true ) ) {
$scripts->set_translations( $handle );
}
}
/**
* Register all package scripts.
*/
function jetpack_seo_register_package_scripts( $scripts ) {
// Load build constants
$build_constants = require __DIR__ . '/constants.php';
$default_version = ! SCRIPT_DEBUG ? $build_constants['version'] : time();
$extension = '.min.js';
$scripts_dir = __DIR__ . '/scripts';
$scripts_file = $scripts_dir . '/registry.php';
if ( ! file_exists( $scripts_file ) ) {
return;
}
$scripts_data = require $scripts_file;
$plugin_dir = dirname( __FILE__ );
foreach ( $scripts_data as $script_data ) {
$asset_file = $scripts_dir . '/' . $script_data['asset'];
$asset = file_exists( $asset_file ) ? require $asset_file : array();
$dependencies = $asset['dependencies'] ?? array();
$version = $asset['version'] ?? $default_version;
jetpack_seo_override_script(
$scripts,
$script_data['handle'],
$build_constants['build_url'] . 'scripts/' . $script_data['path'] . $extension,
$dependencies,
$version,
true
);
}
}
add_action( 'wp_default_scripts', 'jetpack_seo_register_package_scripts' );
@@ -0,0 +1,11 @@
<?php
/**
* Script registry - Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
return array(
);
@@ -0,0 +1,73 @@
<?php
/**
* Style registration - Auto-generated by build process.
* Do not edit this file manually.
*
* Note: These styles can be overridden by calling jetpack_seo_override_style()
* in lib/client-assets.php for complex cases (multiple files, conditional deps, etc.)
*
* @package jetpack_seo
*/
/**
* Registers a style according to `wp_register_style`. Honors this request by
* deregistering any style by the same handler before registration.
*
* @param WP_Styles $styles WP_Styles instance.
* @param string $handle Name of the stylesheet. Should be unique.
* @param string $src Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory.
* @param array $deps Optional. An array of registered stylesheet handles this stylesheet depends on. Default empty array.
* @param string|bool|null $ver Optional. String specifying stylesheet version number, if it has one, which is added to the URL
* as a query string for cache busting purposes. If version is set to false, a version
* number is automatically added equal to current installed WordPress version.
* If set to null, no version is added.
* @param string $media Optional. The media for which this stylesheet has been defined.
* Default 'all'. Accepts media types like 'all', 'print' and 'screen', or media queries like
* '(orientation: portrait)' and '(max-width: 640px)'.
*/
function jetpack_seo_override_style( $styles, $handle, $src, $deps = array(), $ver = false, $media = 'all' ) {
$style = $styles->query( $handle, 'registered' );
if ( $style ) {
$styles->remove( $handle );
}
$styles->add( $handle, $src, $deps, $ver, $media );
}
/**
* Register all package styles (simple cases only).
* Complex cases should be manually registered in lib/client-assets.php.
*
* @param WP_Styles $styles WP_Styles instance.
*/
function jetpack_seo_register_package_styles( $styles ) {
// Load build constants
$build_constants = require __DIR__ . '/constants.php';
$default_version = ! SCRIPT_DEBUG ? $build_constants['version'] : time();
$suffix = '.min';
$styles_dir = __DIR__ . '/styles';
$styles_file = $styles_dir . '/registry.php';
if ( ! file_exists( $styles_file ) ) {
return;
}
$styles_data = require $styles_file;
$plugin_dir = dirname( __FILE__ );
foreach ( $styles_data as $style_data ) {
jetpack_seo_override_style(
$styles,
$style_data['handle'],
$build_constants['build_url'] . 'styles/' . $style_data['path'] . $suffix . '.css',
$style_data['dependencies'],
$default_version
);
// Enable RTL support (WordPress automatically loads -rtl.css variant)
$styles->add_data( $style_data['handle'], 'rtl', 'replace' );
$styles->add_data( $style_data['handle'], 'suffix', $suffix );
}
}
add_action( 'wp_default_styles', 'jetpack_seo_register_package_styles' );
@@ -0,0 +1,11 @@
<?php
/**
* Style registry - Auto-generated by build process.
* Do not edit this file manually.
*
* @package jetpack_seo
*/
return array(
);
@@ -0,0 +1,824 @@
<?php
/**
* Jetpack SEO — the visibility command center for WordPress sites.
*
* Registers the `admin.php?page=jetpack-seo` screen via Admin_Menu so it is
* reachable on self-hosted, Atomic/WoW, and Simple sites alike, and loads the
* `@wordpress/build` (wp-build) dashboard bundle that renders it.
*
* @package automattic/jetpack-seo-package
*/
namespace Automattic\Jetpack\SEO;
use Automattic\Jetpack\Admin_UI\Admin_Menu;
use Automattic\Jetpack\Modules;
use Automattic\Jetpack\Status\Host;
use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
use Jetpack_SEO_Titles;
use Jetpack_SEO_Utils;
use Jetpack_Sitemap_Librarian;
/**
* The main Initializer class. Registers the admin menu and loads the wp-build
* dashboard, bootstrapping the React app's initial state onto the page.
*/
class Initializer {
/**
* Jetpack SEO package version.
*
* @var string
*/
const PACKAGE_VERSION = '0.3.1';
/**
* Filter name that gates the entire Jetpack SEO surface.
*
* When this filter returns true, the package registers its admin menu and
* loads the wp-build dashboard. Default false before release - when the
* filter is off the package registers no admin menu and no assets, and
* changes nothing about the existing Jetpack UI.
*
* @var string
*/
const FEATURE_FILTER = 'rsm_jetpack_seo';
/**
* URL-facing menu slug (`admin.php?page=jetpack-seo`).
*/
const MENU_SLUG = 'jetpack-seo';
/**
* Slug emitted by `@wordpress/build` (`wpPlugin.pages[0]`). wp-build's
* auto-generated enqueue callback only fires when `$screen->id` matches
* this value, so we alias the screen id to it via `current_screen` without
* changing the user-facing URL.
*/
const WP_BUILD_SLUG = 'jetpack-seo-dashboard';
/**
* Render function generated by `@wordpress/build` into
* `build/pages/jetpack-seo-dashboard/page-wp-admin.php`. Naming convention:
* `{wpPlugin.name}_{page-with-underscores}_wp_admin_render_page`.
*/
const WP_BUILD_RENDER_FN = 'jetpack_seo_jetpack_seo_dashboard_wp_admin_render_page';
/**
* Key under `window.JetpackScriptData` the React app reads its state from
* (`window.JetpackScriptData.seo`). Must match the JS-side reader in
* `_inc/data/get-overview.ts`.
*/
const SCRIPT_DATA_KEY = 'seo';
/**
* Post-meta keys mirrored from `Jetpack_SEO_Posts` (in plugins/jetpack).
* Duplicated here as literals on purpose: that plugin class is NOT reliably
* loaded in this package's admin context (the `Jetpack_SEO_Utils`
* `class_exists` guard in `get_overview_data()` is there for the same
* reason), so referencing its constants would fatal. Content-coverage
* counting only needs the key strings, which are stable.
*/
const META_DESCRIPTION = 'advanced_seo_description';
const META_SCHEMA_TYPE = 'jetpack_seo_schema_type';
const META_TITLE = 'jetpack_seo_html_title';
const META_NOINDEX = 'jetpack_seo_noindex';
/**
* Option recording whether sitemap generation is enabled.
*
* Read in place of the standalone `sitemaps` module's active state. Module-active
* state is filtered against the modules present on disk, so once that module is
* removed it would read as inactive even for sites that had it on. A one-time
* migration in the Jetpack plugin seeds this option from the site's existing module
* state and keeps it in sync while the legacy module still exists. See
* `Jetpack::migrate_sitemaps_module_to_seo_option()`.
*
* @var string
*/
const SITEMAP_ENABLED_OPTION = 'jetpack_seo_sitemap_enabled';
/**
* Option recording whether canonical URLs are enabled.
*
* Read in place of the standalone `canonical-urls` module's active state. Module-active
* state is filtered against the modules present on disk, so once that module is
* removed it would read as inactive even for sites that had it on. A one-time
* migration in the Jetpack plugin seeds this option from the site's existing module
* state and keeps it in sync while the legacy module still exists. See
* `Jetpack::migrate_canonical_urls_module_to_seo_option()`.
*
* @var string
*/
const CANONICAL_ENABLED_OPTION = 'jetpack_seo_canonical_urls_enabled';
/**
* Option recording whether the Jetpack SEO surface is discoverable on this site.
*
* Gates whether the SEO admin menu registers on self-hosted sites. Seeded once by the
* Jetpack plugin on install/upgrade: fresh installs default to visible, existing
* installs default to hidden and opt in via the legacy Traffic page or My Jetpack.
* WordPress.com (Simple + Atomic) bypasses this option entirely and is always visible.
* Absent until seeded, in which case self-hosted defaults to hidden (the non-disruptive
* default). See {@see self::is_seo_surface_visible()}.
*
* @var string
*/
const VISIBILITY_OPTION = 'jetpack_seo_surface_visible';
/**
* Whether the package has been initialized.
*
* @var bool
*/
private static $initialized = false;
/**
* Initialize the package.
*
* Called from the Jetpack plugin's `late_initialization()` hook.
*
* @return void
*/
public static function init() {
if ( self::$initialized ) {
return;
}
self::$initialized = true;
// Gate the entire SEO surface behind the feature flag.
if ( ! (bool) apply_filters( self::FEATURE_FILTER, false ) ) {
return;
}
// The opt-in endpoint must be reachable even before the surface is visible, so
// existing self-hosted installs can switch to the new experience from the legacy
// Traffic page or My Jetpack (JETPACK-1700). Registered ahead of the cohort gate.
add_action( 'rest_api_init', array( __CLASS__, 'register_optin_route' ) );
// Expose opt-in availability to other admin surfaces (the legacy Traffic-page
// banner reads it via `@automattic/jetpack-script-data`). Hooked here — after the
// feature flag, before the cohort gate — so a still-hidden install gets the signal.
add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_optin_availability' ) );
// Discoverability cohort gate: the SEO surface is auto-discoverable for fresh
// installs and all WordPress.com sites; existing self-hosted installs opt in via
// the legacy Traffic page or My Jetpack (JETPACK-1700). Until it's visible we
// register nothing else here and let those opt-in surfaces drive discovery.
if ( ! self::is_seo_surface_visible() ) {
return;
}
// The admin menu and app shell register whenever the surface is visible, even
// when the `seo-tools` module is inactive, so SEO stays discoverable and can be
// turned on from within the page itself (JETPACK-1700). When the module is off,
// the Overview renders only its "enable SEO tools" affordance.
//
// Priority 1: load the wp-build bundle (and define its render function)
// before `add_menu_item()` runs at the default priority and needs it.
add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
add_action( 'admin_menu', array( __CLASS__, 'add_menu_item' ), 10 );
// The settings surface only comes online once SEO tools are active — there's
// nothing to configure while the module is off, so we don't register its REST
// endpoints until then. Expose the core `blog_public` option to the REST settings
// endpoint so the Settings tab can save search-engine visibility via
// `/wp/v2/settings` (the Jetpack settings endpoint only accepts Jetpack options).
// Writes are still capability-gated by the core settings controller.
if ( self::is_seo_tools_module_active() ) {
// Front-end JSON-LD schema (Article / FAQ). Self-hooks `wp_head`, so it only
// emits on front-end requests.
Schema_Builder::init();
add_action( 'rest_api_init', array( __CLASS__, 'register_rest_settings' ) );
}
/**
* Fires after the Jetpack SEO package is initialized.
*
* @since 0.1.0
*/
do_action( 'jetpack_seo_init' );
}
/**
* Register the admin menu item.
*
* Uses Admin_Menu so the page is reachable on wp-admin across all site
* types. The render callback is wp-build's generated render function when
* the bundle is loaded (i.e. on the SEO page itself, after
* `maybe_load_wp_build()` ran at priority 1); otherwise it falls back to a
* bare mount node so the page never fatals on an unbuilt checkout.
*
* @return void
*/
public static function add_menu_item() {
$callback = function_exists( self::WP_BUILD_RENDER_FN )
? self::WP_BUILD_RENDER_FN
: array( __CLASS__, 'render_fallback' );
Admin_Menu::add_menu(
'SEO',
'SEO',
'manage_options',
self::MENU_SLUG,
$callback,
2
);
}
/**
* On the SEO admin page, load the wp-build bundle, alias the screen id so
* wp-build enqueues its assets, and bootstrap the app's initial state.
*
* Hooked at `admin_menu` priority 1 so polyfills register and the render
* function is defined before `add_menu_item()` runs at priority 10.
*
* @return void
*/
public static function maybe_load_wp_build() {
if ( ! self::is_seo_admin_request() ) {
return;
}
self::load_wp_build();
add_action( 'current_screen', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_script_data' ) );
}
/**
* Load wp-build's generated registration file and register the polyfills
* the bundle depends on. No-op on a fresh checkout before `pnpm build`, in
* which case `add_menu_item()` falls back to {@see self::render_fallback()}.
*
* @return void
*/
private static function load_wp_build() {
$build_index = dirname( __DIR__ ) . '/build/build.php';
if ( ! file_exists( $build_index ) ) {
return;
}
require_once $build_index;
WP_Build_Polyfills::register(
'jetpack-seo',
array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
);
}
/**
* Alias the current screen id to wp-build's expected slug so its
* auto-generated enqueue callback fires for our user-facing page.
*
* @param \WP_Screen|null $screen The current screen object (passed by WP).
* @return void
*/
public static function alias_screen_id_for_wp_build( $screen ) {
if ( ! is_object( $screen ) ) {
return;
}
$screen->id = self::WP_BUILD_SLUG;
}
/**
* Bootstrap the React app's initial state onto `window.JetpackScriptData.seo`.
*
* Because wp-build pages load as ES modules, `wp_localize_script` can't
* attach data to them; the shared `jetpack_admin_js_script_data` filter
* (printed by the Script_Data package onto the `jetpack-script-data` handle
* the bundle already depends on) is the supported channel. Mirrors Podcast
* and Newsletter.
*
* @param array $data Script data being injected onto the page.
* @return array
*/
public static function inject_script_data( $data ) {
if ( ! is_array( $data ) ) {
$data = array();
}
$data[ self::SCRIPT_DATA_KEY ]['overview'] = self::get_overview_data();
$data[ self::SCRIPT_DATA_KEY ]['settings'] = self::get_settings_data();
$data[ self::SCRIPT_DATA_KEY ]['google_verify'] = self::get_google_verify_data();
$data[ self::SCRIPT_DATA_KEY ]['ai'] = self::get_ai_data();
$data[ self::SCRIPT_DATA_KEY ]['site'] = self::get_site_data();
return $data;
}
/**
* Expose whether this install should be offered the SEO opt-in, onto
* `window.JetpackScriptData.seo.optin_available` for other admin surfaces (e.g. the
* legacy Traffic-page banner). Only hooked when the feature flag is on, so the field is
* simply absent otherwise.
*
* @param array $data Script data being injected onto the page.
* @return array
*/
public static function inject_optin_availability( $data ) {
if ( ! is_array( $data ) ) {
$data = array();
}
$data[ self::SCRIPT_DATA_KEY ]['optin_available'] = self::is_optin_available();
// Read by the legacy Traffic page to hide its SEO / Sitemaps sections once the
// site is on the new experience (fresh install / opted-in / WordPress.com), so the
// two surfaces never show at once. The legacy sections stay for self-hosted installs
// that haven't opted in.
$data[ self::SCRIPT_DATA_KEY ]['surface_visible'] = self::is_seo_surface_visible();
return $data;
}
/**
* Fallback render used when the wp-build artifact is missing (unbuilt
* checkout). Renders a bare wrapper so the page loads without the app.
*
* @return void
*/
public static function render_fallback() {
echo '<div class="wrap"><h1>SEO</h1></div>';
}
/**
* Whether the current request targets the SEO admin page.
*
* @return bool
*/
private static function is_seo_admin_request() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
return false;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
return self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
}
/**
* Whether the `seo-tools` Jetpack module is currently active.
*
* @return bool
*/
private static function is_seo_tools_module_active() {
if ( ! class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
return false;
}
return ( new Modules() )->is_active( 'seo-tools' );
}
/**
* Whether sitemap generation is enabled.
*
* Reads the durable {@see self::SITEMAP_ENABLED_OPTION} flag. The default is only
* used when the option is absent (for example before the Jetpack plugin's migration
* has run on a freshly upgraded site), in which case it falls back to the live
* `sitemaps` module state so behavior is unchanged in that gap.
*
* @param Modules $modules Modules instance to read live module state from.
* @return bool
*/
private static function is_sitemap_enabled( Modules $modules ) {
$enabled = get_option( self::SITEMAP_ENABLED_OPTION, null );
// Only fall back to the live module state when the durable option is absent.
// Passing it as get_option()'s default would evaluate it on every call, since
// PHP resolves function arguments eagerly even when the option exists.
if ( null === $enabled ) {
$enabled = $modules->is_active( 'sitemaps' );
}
return (bool) $enabled;
}
/**
* The public URL of the generated XML sitemap, or an empty string when none
* is currently reachable.
*
* A sitemap is only reachable when generation is enabled, the site is public
* (Jetpack does not load the Sitemaps module on sites that discourage search
* engines), and the master sitemap has actually been generated — the Jetpack
* plugin builds it via cron 115 minutes after activation, so the URL 404s
* until then. Callers treat an empty string as "not yet reachable" and skip
* linking to it.
*
* {@see Jetpack_Sitemap_Librarian} and jetpack_sitemap_uri() live in the
* Jetpack plugin's Sitemaps module (loaded only for an active module on a
* public site), so both are guarded; in the package-only context they are
* absent and the sitemap is reported as not reachable.
*
* @param bool $sitemap_active Whether sitemap generation is enabled.
* @return string The sitemap URL, or '' when not reachable.
*/
private static function get_reachable_sitemap_url( $sitemap_active ) {
// Jetpack only serves sitemaps when generation is on and the site is public.
if ( ! $sitemap_active || (int) get_option( 'blog_public', 1 ) !== 1 ) {
return '';
}
// The Sitemaps module (the librarian class, the `JP_MASTER_SITEMAP_TYPE`
// constant, and the `jp_sitemap_filename()` / `jetpack_sitemap_uri()`
// helpers) all live together in plugins/jetpack and load as a unit, so this
// single guard covers every symbol used below.
if (
! class_exists( 'Jetpack_Sitemap_Librarian' )
|| ! defined( 'JP_MASTER_SITEMAP_TYPE' )
|| ! function_exists( 'jp_sitemap_filename' )
|| ! function_exists( 'jetpack_sitemap_uri' )
) {
return '';
}
// The master sitemap is stored as a post once the cron generation run
// completes; until then there is nothing to link to.
// `jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE )` is the master file name
// ('sitemap.xml'); inlined so this stays one (untestable-in-package) line.
// @phan-suppress-next-line PhanUndeclaredFunction,PhanUndeclaredClassMethod -- guarded above; symbols live in plugins/jetpack.
$master = ( new Jetpack_Sitemap_Librarian() )->read_sitemap_data( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ), JP_MASTER_SITEMAP_TYPE );
if ( null === $master ) {
return '';
}
// esc_url_raw (not esc_url): the value is transported via script data and
// rendered by React, so it must not be HTML-entity-encoded (e.g. the
// plain-permalink `?jetpack-sitemap=` form keeps its raw `&`).
// @phan-suppress-next-line PhanUndeclaredFunction -- jp_sitemap_filename()/jetpack_sitemap_uri() live in plugins/jetpack, guarded by function_exists.
return esc_url_raw( (string) jetpack_sitemap_uri( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ) ) );
}
/**
* Whether canonical URLs are enabled.
*
* Reads the durable {@see self::CANONICAL_ENABLED_OPTION} flag. The default is only
* used when the option is absent (for example before the Jetpack plugin's migration
* has run on a freshly upgraded site), in which case it falls back to the live
* `canonical-urls` module state so behavior is unchanged in that gap.
*
* @param Modules $modules Modules instance to read live module state from.
* @return bool
*/
private static function is_canonical_enabled( Modules $modules ) {
$enabled = get_option( self::CANONICAL_ENABLED_OPTION, null );
// Only fall back to the live module state when the durable option is absent.
// Passing it as get_option()'s default would evaluate it on every call, since
// PHP resolves function arguments eagerly even when the option exists.
if ( null === $enabled ) {
$enabled = $modules->is_active( 'canonical-urls' );
}
return (bool) $enabled;
}
/**
* Whether the Jetpack SEO surface should be discoverable (admin menu registered).
*
* WordPress.com sites (Simple + Atomic) are always discoverable — how SEO presents
* there is a Dotcom decision, independent of the self-hosted rollout. On self-hosted
* sites the durable {@see self::VISIBILITY_OPTION} cohort flag decides: fresh installs
* are seeded visible, existing installs stay hidden until they opt in. Defaults to
* hidden when the option is absent (e.g. before the plugin's seed has run), so an
* existing site is never surprised by the new surface before its cohort is recorded.
*
* @return bool
*/
public static function is_seo_surface_visible() {
if ( class_exists( 'Automattic\\Jetpack\\Status\\Host' ) && ( new Host() )->is_wpcom_platform() ) {
return true;
}
return (bool) get_option( self::VISIBILITY_OPTION, false );
}
/**
* Whether to offer an existing install the chance to opt into the new SEO experience.
*
* The single source of truth for the opt-in surfaces (legacy Traffic-page banner, My
* Jetpack card). True only when the SEO product is available (the {@see self::FEATURE_FILTER}
* flag is on) and the surface isn't visible yet — and since {@see self::is_seo_surface_visible()}
* already returns true for WordPress.com and for self-hosted installs that have opted in,
* "not visible" cleanly means "a self-hosted install that hasn't opted in".
*
* @return bool
*/
public static function is_optin_available() {
return (bool) apply_filters( self::FEATURE_FILTER, false ) && ! self::is_seo_surface_visible();
}
/**
* Build the aggregated Overview state the dashboard renders.
*
* @return array
*/
public static function get_overview_data() {
$modules = new Modules();
// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
$seo_enabled = class_exists( 'Jetpack_SEO_Utils' ) && Jetpack_SEO_Utils::is_enabled_jetpack_seo();
$codes = get_option( 'verification_services_codes', array() );
if ( ! is_array( $codes ) ) {
$codes = array();
}
return array(
'site_visibility' => array(
'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
// Read the durable SEO option (seeded/synced from the `sitemaps` module
// by the Jetpack plugin) so the state survives the module's removal. The
// reachable sitemap URL + "View" link live on the Settings tab.
'sitemap_active' => self::is_sitemap_enabled( $modules ),
'seo_tools_active' => $modules->is_active( 'seo-tools' ),
),
// Per-service booleans (a code is set or not) for the Overview's
// Site verification card.
'site_verification' => array(
'google' => ! empty( $codes['google'] ),
'bing' => ! empty( $codes['bing'] ),
'pinterest' => ! empty( $codes['pinterest'] ),
'yandex' => ! empty( $codes['yandex'] ),
'facebook' => ! empty( $codes['facebook'] ),
),
'content_coverage' => self::get_content_coverage(),
'plan' => array(
'seo_enabled_for_site' => $seo_enabled,
),
);
}
/**
* Factual content-coverage counts for the Overview card: how many published
* posts/pages have each SEO field set. State, not a score — the card shows
* proportions + raw counts and lets the admin decide what matters.
*
* @return array{total:int,with_schema:int,with_title:int,with_description:int,with_search_visible:int}
*/
private static function get_content_coverage() {
$post_types = array( 'post', 'page' );
$total = 0;
foreach ( $post_types as $post_type ) {
$counts = wp_count_posts( $post_type );
$total += isset( $counts->publish ) ? (int) $counts->publish : 0;
}
// Search-engine visibility is the inverse of the per-post noindex meta: a
// post is visible unless it's explicitly set to noindex (stored as '1'), so
// most posts (no meta row) count as visible.
$noindexed = self::count_published_with_meta( $post_types, self::META_NOINDEX, '1' );
return array(
'total' => $total,
'with_schema' => self::count_published_with_meta( $post_types, self::META_SCHEMA_TYPE ),
'with_title' => self::count_published_with_meta( $post_types, self::META_TITLE ),
'with_description' => self::count_published_with_meta( $post_types, self::META_DESCRIPTION ),
'with_search_visible' => max( 0, $total - $noindexed ),
);
}
/**
* Count published posts/pages whose meta is set. With no `$value`, counts a
* non-empty string meta; with a `$value`, counts an exact match.
*
* @param string[] $post_types Post types to count across.
* @param string $meta_key Meta key to test.
* @param string|null $value Exact value to match, or null for "non-empty".
* @return int
*/
private static function count_published_with_meta( $post_types, $meta_key, $value = null ) {
$clause = null === $value
? array(
'key' => $meta_key,
'value' => '',
'compare' => '!=',
)
: array(
'key' => $meta_key,
'value' => $value,
);
$query = new \WP_Query(
array(
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => 1,
'fields' => 'ids',
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Overview snapshot; one count query per metric on the SEO page only.
'meta_query' => array( $clause ),
)
);
return (int) $query->found_posts;
}
/**
* Site identity used to render the homepage search/social previews on the
* Settings tab: title, URL, and representative images. The front-page
* description that completes the preview is read from the Settings form
* (it's editable there), not bootstrapped here.
*
* @return array
*/
public static function get_site_data() {
$icon_url = (string) get_site_icon_url();
$logo_id = (int) get_theme_mod( 'custom_logo' );
$logo_url = $logo_id ? (string) wp_get_attachment_image_url( $logo_id, 'full' ) : '';
return array(
'title' => (string) get_bloginfo( 'name' ),
'url' => (string) home_url(),
'icon' => $icon_url,
'image' => $logo_url ? $logo_url : $icon_url,
);
}
/**
* Expose the core `blog_public` option to the REST settings endpoint.
*
* Search-engine visibility is a WordPress core option, not a Jetpack one,
* so the Settings tab saves it through `/wp/v2/settings` — which only
* round-trips settings registered with `show_in_rest`. The core settings
* controller enforces the `manage_options` capability on writes.
*
* @return void
*/
public static function register_rest_settings() {
register_setting(
'reading',
'blog_public',
array(
'show_in_rest' => true,
'type' => 'integer',
'default' => 1,
)
);
}
/**
* Register the opt-in REST route that switches an existing self-hosted install over to
* the new SEO experience.
*
* Lives on the `jetpack/v4` namespace and is registered ahead of the cohort gate, so a
* site whose SEO surface is still hidden can reach it from the legacy Traffic page or
* My Jetpack. See {@see self::handle_optin()}.
*
* @return void
*/
public static function register_optin_route() {
register_rest_route(
'jetpack/v4',
'/seo/opt-in',
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array( __CLASS__, 'handle_optin' ),
'permission_callback' => function () {
return current_user_can( 'manage_options' );
},
)
);
}
/**
* Opt an existing install into the new SEO experience: mark the surface visible and
* activate the `seo-tools` module, then hand back the dashboard URL to redirect to.
*
* Idempotent — re-opting-in is harmless. `Modules::activate()` is called with
* `$exit = false, $redirect = false`; the defaults would `exit()` and send a 302,
* which break a REST response.
*
* @return \WP_REST_Response
*/
public static function handle_optin() {
update_option( self::VISIBILITY_OPTION, true );
if ( class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
( new Modules() )->activate( 'seo-tools', false, false );
}
return rest_ensure_response(
array(
'success' => true,
'redirect' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
)
);
}
/**
* Build the editable Settings state the Settings tab hydrates from.
*
* Read-only bootstrap only. Writes go through the existing
* `/jetpack/v4/settings` REST endpoint, which already validates and
* sanitizes each of these fields — this package registers no settings
* endpoint of its own. The reads here mirror the options/helpers that
* endpoint round-trips so the form hydrates without a request.
*
* @return array
*/
public static function get_settings_data() {
$modules = new Modules();
// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Titles lives in plugins/jetpack and is guarded by class_exists.
$title_formats = class_exists( 'Jetpack_SEO_Titles' ) ? Jetpack_SEO_Titles::get_custom_title_formats() : array();
// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
$front_page_desc = class_exists( 'Jetpack_SEO_Utils' ) ? Jetpack_SEO_Utils::get_front_page_meta_description() : '';
$codes = get_option( 'verification_services_codes', array() );
if ( ! is_array( $codes ) ) {
$codes = array();
}
$sitemap_active = self::is_sitemap_enabled( $modules );
return array(
'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
// Read the durable SEO option (seeded/synced from the `sitemaps` module
// by the Jetpack plugin) so the state survives the module's removal.
'sitemap_active' => $sitemap_active,
// Empty until the sitemap is genuinely reachable, so the Settings tab can
// link to it only once it won't 404 (it's built by cron after activation).
'sitemap_url' => self::get_reachable_sitemap_url( $sitemap_active ),
// Read the durable SEO option (seeded/synced from the `canonical-urls` module
// by the Jetpack plugin) so the state survives the module's removal.
'canonical_active' => self::is_canonical_enabled( $modules ),
// Cast to object so an empty format set serializes as `{}`, not `[]`.
'title_formats' => (object) $title_formats,
'front_page_description' => (string) $front_page_desc,
'verification' => array(
'google' => isset( $codes['google'] ) ? (string) $codes['google'] : '',
'bing' => isset( $codes['bing'] ) ? (string) $codes['bing'] : '',
'pinterest' => isset( $codes['pinterest'] ) ? (string) $codes['pinterest'] : '',
'yandex' => isset( $codes['yandex'] ) ? (string) $codes['yandex'] : '',
'facebook' => isset( $codes['facebook'] ) ? (string) $codes['facebook'] : '',
),
);
}
/**
* Build the Google site-verification state for the Settings tab.
*
* The Settings verification card lets a connected user verify with Google via a
* WordPress.com keyring OAuth popup (in addition to pasting a meta-tag code). This
* bootstraps the keyring connect URL and whether the current user is connected —
* the live verified status is fetched client-side from `/jetpack/v4/verify-site/google`
* (a wpcom round-trip we don't want to make on every page load).
*
* Both `Keyring_Helper` (Publicize package) and the connection `Manager` are provided
* by the host Jetpack plugin, so they're guarded with `class_exists` like the
* `Jetpack_SEO_*` helpers. On a disconnected self-hosted site `is_connected` is false
* and the UI falls back to manual code entry only.
*
* @return array
*/
public static function get_google_verify_data() {
$connect_url = '';
if ( class_exists( 'Automattic\\Jetpack\\Publicize\\Keyring_Helper' ) ) {
// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Publicize package is provided by the host plugin.
$connect_url = (string) \Automattic\Jetpack\Publicize\Keyring_Helper::connect_url( 'google_site_verification', 'other' );
}
$is_connected = false;
if ( class_exists( 'Automattic\\Jetpack\\Connection\\Manager' ) ) {
// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Connection package is provided by the host plugin.
$is_connected = ( new \Automattic\Jetpack\Connection\Manager() )->is_user_connected();
}
return array(
'connect_url' => $connect_url,
'is_connected' => (bool) $is_connected,
);
}
/**
* Build the AI tab's initial state.
*
* The AI SEO Enhancer auto-generates SEO titles/descriptions/alt-text in the
* editor (the generation itself is wpcom/AI-Assistant side); this exposes only
* its persisted on/off toggle and whether it's available. Availability mirrors
* the legacy Traffic page: the `ai_seo_enhancer_enabled` feature filter must be
* on (it still depends on AI being available) AND the site's plan must support
* the `ai-seo-enhancer` feature. The toggle writes through the existing
* `/jetpack/v4/settings` endpoint (`ai_seo_enhancer_enabled`).
*
* @return array
*/
public static function get_ai_data() {
$filter_on = (bool) apply_filters( 'ai_seo_enhancer_enabled', true );
// Current_Plan is provided by the host Jetpack plugin, not a package
// dependency — guard like the Jetpack_SEO_* helpers above.
$plan_supports = class_exists( 'Automattic\\Jetpack\\Current_Plan' )
// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded by class_exists; host plugin provides the class.
&& \Automattic\Jetpack\Current_Plan::supports( 'ai-seo-enhancer' );
return array(
'enhancer' => array(
'available' => $filter_on && $plan_supports,
'enabled' => (bool) get_option( 'ai_seo_enhancer_enabled', false ),
),
);
}
}
@@ -0,0 +1,208 @@
<?php
/**
* JSON-LD Schema.org markup emitter.
*
* Emits per-post structured data into the document `<head>`: Article (the
* default for posts) and FAQPage (when the post uses `core/details` blocks).
* The type follows the per-post `jetpack_seo_schema_type` override when set,
* otherwise a sensible default by post type. Emission is gated on
* `Jetpack_SEO_Utils::is_enabled_jetpack_seo()`.
*
* Organization / LocalBusiness (site-level) and HowTo are intentionally out of
* scope here — they need backing config / structured input. See JETPACK-1701
* (Expanded schema markup project).
*
* @package automattic/jetpack-seo-package
*/
namespace Automattic\Jetpack\SEO;
use Jetpack_SEO_Posts;
use Jetpack_SEO_Utils;
use WP_Post;
/**
* Emits Schema.org JSON-LD into the document head.
*/
class Schema_Builder {
/**
* Max words kept for a schema `description`, so a long post body doesn't
* dump its full content into the markup.
*/
const DESCRIPTION_MAX_WORDS = 55;
/**
* Wire the front-end emitter.
*
* @return void
*/
public static function init() {
add_action( 'wp_head', array( __CLASS__, 'emit' ), 5 );
}
/**
* Build and echo the JSON-LD block for the current singular request.
*
* @return void
*/
public static function emit() {
// Both plugin classes must be loaded — they're not guaranteed in every
// context, and build_for_post() calls Jetpack_SEO_Posts directly.
// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack; guarded by the class_exists check on the same line.
if ( ! class_exists( 'Jetpack_SEO_Utils' ) || ! class_exists( 'Jetpack_SEO_Posts' ) || ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
return;
}
if ( ! is_singular() ) {
return;
}
$node = self::build_for_post( get_queried_object() );
if ( ! $node ) {
return;
}
$doc = array( '@context' => 'https://schema.org' ) + $node;
printf(
'<script type="application/ld+json">%s</script>',
// Default flags escape forward slashes — important inside <script>
// so a "</script>" in the data can't break out of the block.
wp_json_encode( $doc, JSON_UNESCAPED_UNICODE ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
);
}
/**
* Build the JSON-LD node for the queried post.
*
* @param WP_Post|null $post The queried post.
* @return array|null
*/
private static function build_for_post( $post ) {
if ( ! ( $post instanceof WP_Post ) ) {
return null;
}
// Only emit structured data for published content. Previews, drafts, and
// private posts are viewable by logged-in users (and may be edge-cached),
// so we must not output JSON-LD for anything that isn't publicly published.
if ( 'publish' !== $post->post_status ) {
return null;
}
// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Posts lives in plugins/jetpack; emit() guards on class_exists.
$override = Jetpack_SEO_Posts::get_post_schema_type( $post );
$type = '' !== $override ? $override : self::default_schema_for_post( $post );
switch ( $type ) {
case 'faq':
return self::build_faq( $post );
case 'article':
return self::build_article( $post );
default:
return null;
}
}
/**
* Default Schema type for a post when the user has not set an override:
* Article for standard posts, none for pages, attachments, or custom types.
*
* @param WP_Post $post The post.
* @return string
*/
private static function default_schema_for_post( WP_Post $post ) {
// Only standard posts get Article schema by default; everything else
// (pages, attachments, custom post types) requires an explicit override.
return 'post' === $post->post_type ? 'article' : '';
}
/**
* Article JSON-LD.
*
* @param WP_Post $post The post.
* @return array
*/
private static function build_article( WP_Post $post ) {
$node = array(
'@type' => 'Article',
'headline' => wp_strip_all_tags( get_the_title( $post ) ),
'datePublished' => get_post_time( 'c', true, $post ),
'dateModified' => get_post_modified_time( 'c', true, $post ),
'mainEntityOfPage' => array(
'@type' => 'WebPage',
'@id' => get_permalink( $post ),
),
'author' => array(
'@type' => 'Person',
'name' => get_the_author_meta( 'display_name', (int) $post->post_author ),
),
);
$image = get_the_post_thumbnail_url( $post, 'full' );
if ( $image ) {
$node['image'] = $image;
}
// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Posts lives in plugins/jetpack; emit() guards on class_exists.
$description = Jetpack_SEO_Posts::get_post_description( $post );
if ( $description ) {
// Cap it: get_post_description() falls back to full post_content, which
// would otherwise dump the whole body into the markup.
$node['description'] = wp_trim_words( wp_strip_all_tags( $description ), self::DESCRIPTION_MAX_WORDS, '' );
}
return $node;
}
/**
* FAQPage JSON-LD, parsed from `core/details` blocks (summary = question,
* rendered content = answer). Returns null when the post has none, so we
* never emit an empty/invalid FAQPage.
*
* @param WP_Post $post The post.
* @return array|null
*/
private static function build_faq( WP_Post $post ) {
if ( ! function_exists( 'parse_blocks' ) ) {
return null;
}
$items = array();
foreach ( parse_blocks( $post->post_content ) as $block ) {
if ( 'core/details' !== ( $block['blockName'] ?? '' ) ) {
continue;
}
$question = trim( (string) ( $block['attrs']['summary'] ?? '' ) );
// Render only the inner blocks for the answer. Rendering the whole
// core/details block would re-include the <summary> (the question).
$answer_html = '';
foreach ( $block['innerBlocks'] ?? array() as $inner_block ) {
$answer_html .= render_block( $inner_block );
}
$answer = trim( wp_strip_all_tags( $answer_html ) );
if ( '' === $question || '' === $answer ) {
continue;
}
$items[] = array(
'@type' => 'Question',
'name' => $question,
'acceptedAnswer' => array(
'@type' => 'Answer',
'text' => $answer,
),
);
}
if ( empty( $items ) ) {
return null;
}
return array(
'@type' => 'FAQPage',
'mainEntity' => $items,
);
}
}