share( Services\SitemapGenerator::class, static fn( Container $c ) => new Services\SitemapGenerator( $c->get( Options::class ) ) ); } public function boot( Container $container ): void { // A sitemap for people: the page a visitor lands on when they cannot // find something. Available as a shortcode and as a block. add_shortcode( 'airanksuite_html_sitemap', static function ( $atts ): string { $atts = shortcode_atts( array( 'types' => 'post,page', 'limit' => 300, 'order' => 'title', 'show_date' => '', 'headings' => '1' ), is_array( $atts ) ? $atts : array(), 'airanksuite_html_sitemap' ); return Services\HtmlSitemap::render( $atts ); } ); add_action( 'init', static function (): void { if ( ! function_exists( 'register_block_type' ) ) { return; } register_block_type( 'ai-rank-suite/html-sitemap', array( 'api_version' => 2, 'title' => __( 'HTML sitemap', 'ai-rank-suite' ), 'description' => __( 'Every page of the site, listed for readers — without the ones you keep out of search.', 'ai-rank-suite' ), 'category' => 'ai-rank-suite', 'icon' => 'networking', 'attributes' => array( 'types' => array( 'type' => 'array', 'default' => array( 'post', 'page' ) ), 'limit' => array( 'type' => 'number', 'default' => 300 ), 'order' => array( 'type' => 'string', 'default' => 'title' ), 'showDate' => array( 'type' => 'boolean', 'default' => false ), ), 'render_callback' => static fn( array $attributes ): string => Services\HtmlSitemap::render( array( 'types' => (array) ( $attributes['types'] ?? array( 'post', 'page' ) ), 'limit' => (int) ( $attributes['limit'] ?? 300 ), 'order' => (string) ( $attributes['order'] ?? 'title' ), 'show_date' => ! empty( $attributes['showDate'] ), ) ), 'supports' => array( 'html' => false ), ) ); }, 11 ); add_action( 'init', array( self::class, 'add_rewrite' ) ); add_action( 'parse_request', array( self::class, 'route_request' ), 0 ); add_filter( 'query_vars', static function ( array $vars ): array { return array_merge( $vars, array( 'airanksuite_sitemap', 'airanksuite_sitemap_type', 'airanksuite_sitemap_page', 'airanksuite_sitemap_xsl' ) ); } ); add_filter( 'request', static function ( array $vars ): array { // WordPress 7 adds its own immutable sitemap.xml rewrite before // plugin rules. Claim that parsed request for our replacement index. if ( 'index' === ( $vars['sitemap'] ?? '' ) ) { $vars['airanksuite_sitemap'] = 'index'; unset( $vars['sitemap'] ); } return $vars; } ); add_filter( 'redirect_canonical', static function ( $redirect ) { $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_URI'] ) ) : ''; $filename = basename( (string) wp_parse_url( $request_uri, PHP_URL_PATH ) ); return preg_match( '/^(?:sitemap(?:_index|-index)?|sitemap-tax-[a-z0-9_-]+-[0-9]+|sitemap-[a-z0-9_-]+-[0-9]+|news-sitemap|video-sitemap)\.xml$/', $filename ) ? false : $redirect; }, 10, 2 ); Guard::action( 'template_redirect', array( $this, 'serve' ), 0 ); add_action( 'rest_api_init', array( $this, 'routes' ) ); // Our sitemap replaces the core one to avoid two competing indexes. add_filter( 'wp_sitemaps_enabled', function ( bool $enabled ): bool { return empty( $this->settings()['enabled'] ) ? $enabled : false; } ); // Advertise the sitemap in robots.txt. Guard::filter( 'robots_txt', function ( string $output ): string { if ( empty( $this->settings()['enabled'] ) ) { return $output; } return $output . "\nSitemap: " . esc_url_raw( home_url( '/sitemap.xml' ) ) . "\n"; }, 5 ); foreach ( array( 'save_post', 'deleted_post', 'edited_terms' ) as $hook ) { add_action( $hook, array( Services\SitemapGenerator::class, 'flush_cache' ) ); } } public static function add_rewrite(): void { add_rewrite_rule( '^sitemap\.xml$', 'index.php?airanksuite_sitemap=index', 'top' ); // Yoast, Rank Math and AIOSEO all publish sitemap_index.xml, so that is // the URL already submitted in Search Console on most sites people // migrate from. Serving the same index under both spellings means a // migration does not silently orphan the submitted sitemap. add_rewrite_rule( '^sitemap_index\.xml$', 'index.php?airanksuite_sitemap=index', 'top' ); add_rewrite_rule( '^sitemap-index\.xml$', 'index.php?airanksuite_sitemap=index', 'top' ); add_rewrite_rule( '^sitemap\.xsl$', 'index.php?airanksuite_sitemap_xsl=1', 'top' ); add_rewrite_rule( '^news-sitemap\.xml$', 'index.php?airanksuite_sitemap=news', 'top' ); add_rewrite_rule( '^video-sitemap\.xml$', 'index.php?airanksuite_sitemap=video', 'top' ); add_rewrite_rule( '^sitemap-tax-([a-z0-9_-]+)-([0-9]+)\.xml$', 'index.php?airanksuite_sitemap=tax&airanksuite_sitemap_type=$matches[1]&airanksuite_sitemap_page=$matches[2]', 'top' ); add_rewrite_rule( '^sitemap-([a-z0-9_-]+)-([0-9]+)\.xml$', 'index.php?airanksuite_sitemap=posts&airanksuite_sitemap_type=$matches[1]&airanksuite_sitemap_page=$matches[2]', 'top' ); } /** * Route the fixed sitemap filenames even when a host serves stale rewrites. * * @param \WP $wp Current WordPress request parser. */ public static function route_request( \WP $wp ): void { $request = trim( (string) $wp->request, '/' ); if ( 'sitemap.xml' === $request || 'sitemap_index.xml' === $request || 'sitemap-index.xml' === $request ) { $wp->query_vars['airanksuite_sitemap'] = 'index'; } elseif ( 'sitemap.xsl' === $request ) { $wp->query_vars['airanksuite_sitemap_xsl'] = '1'; } elseif ( 'news-sitemap.xml' === $request ) { $wp->query_vars['airanksuite_sitemap'] = 'news'; } elseif ( 'video-sitemap.xml' === $request ) { $wp->query_vars['airanksuite_sitemap'] = 'video'; } elseif ( preg_match( '/^sitemap-tax-([a-z0-9_-]+)-([0-9]+)\.xml$/', $request, $match ) ) { $wp->query_vars['airanksuite_sitemap'] = 'tax'; $wp->query_vars['airanksuite_sitemap_type'] = $match[1]; $wp->query_vars['airanksuite_sitemap_page'] = $match[2]; } elseif ( preg_match( '/^sitemap-([a-z0-9_-]+)-([0-9]+)\.xml$/', $request, $match ) ) { $wp->query_vars['airanksuite_sitemap'] = 'posts'; $wp->query_vars['airanksuite_sitemap_type'] = $match[1]; $wp->query_vars['airanksuite_sitemap_page'] = $match[2]; } } /** * Serve the requested sitemap document. */ public function serve(): void { $xsl = '1' === get_query_var( 'airanksuite_sitemap_xsl' ); $kind = (string) get_query_var( 'airanksuite_sitemap' ); // Some hosts (and WordPress' own legacy sitemap redirect) can reach // template_redirect before newly flushed rewrite rules are visible. Match // the small, explicit public URL set as a fallback so /sitemap.xml never // gets redirected to the disabled core /wp-sitemap.xml endpoint. if ( ! $xsl && '' === $kind ) { $request = basename( \AiRankSuite\Support\Server::path() ); if ( 'sitemap.xml' === $request || 'sitemap_index.xml' === $request || 'sitemap-index.xml' === $request ) { $kind = 'index'; } elseif ( 'sitemap.xsl' === $request ) { $xsl = true; } elseif ( 'news-sitemap.xml' === $request ) { $kind = 'news'; } elseif ( 'video-sitemap.xml' === $request ) { $kind = 'video'; } elseif ( preg_match( '/^sitemap-tax-([a-z0-9_-]+)-([0-9]+)\.xml$/', $request, $match ) ) { $kind = 'tax'; set_query_var( 'airanksuite_sitemap_type', $match[1] ); set_query_var( 'airanksuite_sitemap_page', $match[2] ); } elseif ( preg_match( '/^sitemap-([a-z0-9_-]+)-([0-9]+)\.xml$/', $request, $match ) ) { $kind = 'posts'; set_query_var( 'airanksuite_sitemap_type', $match[1] ); set_query_var( 'airanksuite_sitemap_page', $match[2] ); } } if ( ! $xsl && '' === $kind ) { return; } $generator = \AiRankSuite\Kernel::service( Services\SitemapGenerator::class ); if ( $xsl ) { header( 'Content-Type: application/xml; charset=UTF-8' ); // XSL document, not HTML output. echo $generator->stylesheet(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped exit; } if ( empty( $this->settings()['enabled'] ) ) { status_header( 404 ); return; } $type = sanitize_key( (string) get_query_var( 'airanksuite_sitemap_type' ) ); $page = max( 1, (int) get_query_var( 'airanksuite_sitemap_page' ) ); $key = Services\SitemapGenerator::CACHE_PREFIX . md5( $kind . '|' . $type . '|' . $page ); $body = get_transient( $key ); if ( ! is_string( $body ) || '' === $body ) { $body = match ( $kind ) { 'index' => $generator->index(), 'posts' => $generator->posts( $type, $page ), 'tax' => $generator->terms( $type ), 'news' => $generator->news(), 'video' => $generator->video(), default => '', }; if ( '' === $body ) { status_header( 404 ); exit; } set_transient( $key, $body, 12 * HOUR_IN_SECONDS ); } status_header( 200 ); header( 'Content-Type: application/xml; charset=UTF-8' ); header( 'X-Robots-Tag: noindex, follow' ); // XML document. echo $body; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped exit; } public function routes(): void { register_rest_route( self::NAMESPACE, '/settings/sitemap', array( array( 'methods' => 'GET', 'callback' => array( $this, 'get_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'enabled' => array( 'type' => 'boolean' ), 'per_page' => array( 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'post_types' => array( 'type' => 'array' ), 'taxonomies' => array( 'type' => 'array' ), 'include_images' => array( 'type' => 'boolean' ), 'include_featured' => array( 'type' => 'boolean' ), 'exclude_ids' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'exclude_terms' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'news_enabled' => array( 'type' => 'boolean' ), 'news_name' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'news_types' => array( 'type' => 'array' ), 'video_enabled' => array( 'type' => 'boolean' ), ), ), ) ); // "Show me the actual XML" — answered without leaving WordPress, and // without asking the customer to open view-source on a file that is // served with an XSL stylesheet the browser will render instead. register_rest_route( self::NAMESPACE, '/sitemap/preview', array( 'methods' => 'GET', 'callback' => array( $this, 'preview' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'kind' => array( 'type' => 'string', 'default' => 'index', 'enum' => array( 'index', 'posts', 'tax', 'news', 'video' ), ), 'type' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_key', ), 'page' => array( 'type' => 'integer', 'default' => 1, 'minimum' => 1, ), ), ) ); register_rest_route( self::NAMESPACE, '/sitemap/flush', array( 'methods' => 'POST', 'callback' => array( $this, 'flush' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ) ); } public function get_settings(): WP_REST_Response { $generator = \AiRankSuite\Kernel::service( Services\SitemapGenerator::class ); return new WP_REST_Response( array( 'settings' => $this->settings(), 'url' => home_url( '/sitemap.xml' ), 'news_url' => home_url( '/news-sitemap.xml' ), 'video_url' => home_url( '/video-sitemap.xml' ), 'total_urls' => $generator->total_urls(), 'breakdown' => $generator->breakdown(), // Slugs alone made the checkbox list read like a database dump; // the label is what the customer recognises. 'post_types' => array_map( static fn( $type ) => array( 'name' => $type->name, 'label' => $type->labels->name ?? $type->name, 'count' => (int) ( wp_count_posts( $type->name )->publish ?? 0 ), ), array_values( array_filter( get_post_types( array( 'public' => true ), 'objects' ), static fn( $type ) => 'attachment' !== $type->name ) ) ), 'taxonomies' => array_map( static fn( $tax ) => array( 'name' => $tax->name, 'label' => $tax->labels->name ?? $tax->name, 'count' => is_wp_error( wp_count_terms( array( 'taxonomy' => $tax->name, 'hide_empty' => true ) ) ) ? 0 : (int) wp_count_terms( array( 'taxonomy' => $tax->name, 'hide_empty' => true ) ), ), array_values( get_taxonomies( array( 'public' => true ), 'objects' ) ) ), 'permalinks' => (bool) get_option( 'permalink_structure' ), ) ); } public function update_settings( WP_REST_Request $request ): WP_REST_Response { $defaults = Services\SitemapGenerator::defaults(); $values = array(); foreach ( array_keys( $defaults ) as $key ) { if ( ! $request->has_param( $key ) ) { continue; } if ( 'news_types' === $key ) { $values[ $key ] = array_values( array_intersect( (array) $request->get_param( $key ), get_post_types( array( 'public' => true ) ) ) ); continue; } if ( 'post_types' === $key ) { $values[ $key ] = array_values( array_intersect( (array) $request->get_param( $key ), get_post_types( array( 'public' => true ) ) ) ); continue; } if ( 'taxonomies' === $key ) { $values[ $key ] = array_values( array_intersect( (array) $request->get_param( $key ), get_taxonomies( array( 'public' => true ) ) ) ); continue; } if ( 'per_page' === $key ) { // The sitemap protocol caps a file at 50,000 URLs. An unbounded // value here would build one enormous file that no crawler // accepts and that times out on the way to producing it. $values[ $key ] = max( 50, min( 50000, (int) $request->get_param( $key ) ) ); continue; } if ( 'exclude_ids' === $key ) { // Normalize on the way in so reopening the field shows exactly // what is in effect, not the typo that was ignored. $ids = array_values( array_unique( array_filter( array_map( 'absint', preg_split( '/[\s,]+/', (string) $request->get_param( $key ) ) ?: array() ) ) ) ); $values[ $key ] = implode( ', ', $ids ); continue; } $values[ $key ] = $request->get_param( $key ); } \AiRankSuite\Kernel::service( Options::class )->set( 'sitemap', $values, $defaults ); Services\SitemapGenerator::flush_cache(); self::add_rewrite(); flush_rewrite_rules(); return $this->get_settings(); } /** * The raw XML of one sitemap file, plus what it costs. */ public function preview( WP_REST_Request $request ): WP_REST_Response|WP_Error { $generator = \AiRankSuite\Kernel::service( Services\SitemapGenerator::class ); $kind = (string) $request['kind']; $type = (string) $request['type']; $page = max( 1, (int) $request['page'] ); $xml = match ( $kind ) { 'index' => $generator->index(), 'posts' => $generator->posts( $type, $page ), 'tax' => $generator->terms( $type ), 'news' => $generator->news(), 'video' => $generator->video(), default => '', }; if ( '' === $xml ) { return new WP_Error( 'airanksuite_sitemap_empty', __( 'That sitemap file is empty — nothing matches its rules.', 'ai-rank-suite' ), array( 'status' => 404 ) ); } // Count entries rather than trusting the settings: a file that claims // 500 URLs and contains 12 is exactly the bug this screen exists to // surface. $urls = substr_count( $xml, '' ); $maps = substr_count( $xml, '' ); $invalid = null === simplexml_load_string( $xml ); return new WP_REST_Response( array( 'kind' => $kind, 'type' => $type, 'page' => $page, 'xml' => $xml, 'bytes' => strlen( $xml ), 'urls' => $urls, 'files' => $maps, 'valid' => ! $invalid, // Google refuses a sitemap above 50,000 URLs or 50 MB // uncompressed; both limits are worth showing before they bite. 'over' => $urls > 50000 || strlen( $xml ) > 50 * MB_IN_BYTES, ) ); } public function flush(): WP_REST_Response { Services\SitemapGenerator::flush_cache(); return $this->get_settings(); } /** @return array */ private function settings(): array { return \AiRankSuite\Kernel::service( Options::class )->get( 'sitemap', Services\SitemapGenerator::defaults() ); } }