*/ public static function defaults(): array { return array( 'enabled' => true, 'per_page' => 200, 'post_types' => array( 'post', 'page' ), 'taxonomies' => array( 'category' ), 'include_images' => true, // The featured image is not in post_content, so a sitemap built // from the content alone leaves out the one image most themes put // at the top of the page. 'include_featured' => true, 'exclude_ids' => '', // Term ids kept out of the taxonomy sitemaps — the twin of // exclude_ids for categories and tags. 'exclude_terms' => '', 'news_enabled' => false, 'news_name' => '', 'news_types' => array( 'post' ), 'video_enabled' => false, ); } /** @return array */ public function settings(): array { return $this->options->get( 'sitemap', self::defaults() ); } /** * Post IDs the user excluded manually. * * @return array */ /** * Term IDs the user excluded manually. * * @return array */ private function excluded_terms(): array { $raw = (string) ( $this->settings()['exclude_terms'] ?? '' ); return array_values( array_filter( array_map( 'absint', preg_split( '/[\s,]+/', $raw ) ?: array() ) ) ); } private function excluded(): array { $raw = (string) $this->settings()['exclude_ids']; if ( '' === trim( $raw ) ) { return array(); } return array_values( array_filter( array_map( 'absint', preg_split( '/[\s,]+/', $raw ) ?: array() ) ) ); } /** * Sitemap index listing every sub-sitemap. */ public function index(): string { $settings = $this->settings(); $entries = array(); foreach ( (array) $settings['post_types'] as $type ) { $pages = (int) ceil( $this->count_posts( $type ) / max( 1, (int) $settings['per_page'] ) ); for ( $i = 1; $i <= $pages; $i++ ) { $entries[] = array( 'loc' => home_url( "/sitemap-{$type}-{$i}.xml" ), 'lastmod' => $this->latest_modified( $type ), ); } } foreach ( (array) $settings['taxonomies'] as $tax ) { if ( $this->count_terms( $tax ) > 0 ) { $entries[] = array( 'loc' => home_url( "/sitemap-tax-{$tax}-1.xml" ), 'lastmod' => $this->latest_in_taxonomy( $tax ), ); } } if ( ! empty( $settings['news_enabled'] ) ) { $entries[] = array( 'loc' => home_url( '/news-sitemap.xml' ), 'lastmod' => '', ); } if ( ! empty( $settings['video_enabled'] ) ) { $entries[] = array( 'loc' => home_url( '/video-sitemap.xml' ), 'lastmod' => '', ); } /** * Filter sitemap index entries. * * @param array $entries Entries with loc/lastmod. */ $entries = (array) apply_filters( 'airanksuite/sitemap/index', $entries ); $xml = '' . "\n"; $xml .= '' . "\n"; $xml .= '' . "\n"; foreach ( $entries as $entry ) { $xml .= "\t\n\t\t" . esc_url( $entry['loc'] ) . "\n"; if ( ! empty( $entry['lastmod'] ) ) { $xml .= "\t\t" . esc_html( $entry['lastmod'] ) . "\n"; } $xml .= "\t\n"; } return $xml . ''; } /** * A single post-type sitemap page. */ public function posts( string $type, int $page ): string { $settings = $this->settings(); if ( ! in_array( $type, (array) $settings['post_types'], true ) ) { return ''; } $per_page = max( 1, (int) $settings['per_page'] ); $posts = get_posts( array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => $per_page, 'offset' => ( max( 1, $page ) - 1 ) * $per_page, 'orderby' => 'modified', 'order' => 'DESC', 'exclude' => $this->excluded(), 'has_password' => false, 'suppress_filters' => false, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query 'meta_query' => array( 'relation' => 'OR', array( 'key' => '_airanksuite_robots', 'compare' => 'NOT EXISTS', ), array( 'key' => '_airanksuite_robots', 'value' => 'noindex', 'compare' => 'NOT LIKE', ), ), ) ); $urls = array(); foreach ( $posts as $post ) { if ( get_post_meta( $post->ID, '_airanksuite_exclude_sitemap', true ) ) { continue; } $url = array( 'loc' => (string) get_permalink( $post ), 'lastmod' => (string) get_post_modified_time( 'c', true, $post ), 'images' => array(), ); if ( ! empty( $settings['include_images'] ) ) { $url['images'] = $this->images_for( $post ); } $urls[] = $url; } return $this->urlset( $urls ); } /** * A taxonomy sitemap. */ public function terms( string $taxonomy ): string { $settings = $this->settings(); if ( ! in_array( $taxonomy, (array) $settings['taxonomies'], true ) ) { return ''; } $terms = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => true, 'number' => max( 1, (int) $settings['per_page'] ), 'exclude' => $this->excluded_terms(), ) ); if ( is_wp_error( $terms ) ) { return $this->urlset( array() ); } /* * A category page changes when a post in it changes, so its lastmod is * the newest published post carrying the term. Without it the taxonomy * file was the only part of the sitemap with no dates at all, and * lastmod is the one hint in a sitemap that Google actually acts on. * One grouped query for the whole page of terms, not one per term. */ $lastmods = $this->term_lastmods( array_map( static fn( $t ) => (int) $t->term_id, $terms ) ); $urls = array(); foreach ( $terms as $term ) { $link = get_term_link( $term ); if ( is_wp_error( $link ) ) { continue; } $urls[] = array( 'loc' => (string) $link, 'lastmod' => (string) ( $lastmods[ (int) $term->term_id ] ?? '' ), 'images' => array(), ); } return $this->urlset( $urls ); } /** * Featured image + content images of a post. * * @return array */ private function images_for( \WP_Post $post ): array { $images = array(); $settings = $this->settings(); if ( ! empty( $settings['include_featured'] ) ) { $thumb = get_the_post_thumbnail_url( $post, 'full' ); if ( $thumb ) { $images[] = (string) $thumb; } } if ( preg_match_all( '/]+src=["\']([^"\']+)["\']/i', (string) $post->post_content, $m ) ) { foreach ( $m[1] as $src ) { if ( str_starts_with( $src, 'http' ) ) { $images[] = $src; } } } return array_slice( array_unique( $images ), 0, 10 ); } /** * Render a urlset document. * * @param array> $urls URLs. */ private function urlset( array $urls ): string { $xml = '' . "\n"; $xml .= '' . "\n"; $xml .= '' . "\n"; foreach ( $urls as $url ) { $xml .= "\t\n\t\t" . esc_url( $url['loc'] ) . "\n"; if ( ! empty( $url['lastmod'] ) ) { $xml .= "\t\t" . esc_html( $url['lastmod'] ) . "\n"; } foreach ( (array) ( $url['images'] ?? array() ) as $image ) { $xml .= "\t\t\n\t\t\t" . esc_url( $image ) . "\n\t\t\n"; } $xml .= "\t\n"; } return $xml . ''; } /** * Human-readable stylesheet so the sitemap does not look broken in a browser. * * An XSL document, not a WordPress page: there is no wp_head() for an * enqueued style to print into. It is a file of its own, read and served * as it is from /sitemap.xsl — the sitemap has to name a stylesheet on its * own origin, and the plugin folder may sit on a CDN host. */ public function stylesheet(): string { $file = AIRANKSUITE_DIR . 'assets/sitemap/sitemap.xsl'; return is_readable( $file ) ? (string) file_get_contents( $file ) : ''; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- a local file shipped with the plugin. } /** * Google News sitemap — articles from the last 48 hours only, per spec. */ public function news(): string { $settings = $this->settings(); if ( empty( $settings['news_enabled'] ) ) { return ''; } $posts = get_posts( array( 'post_type' => (array) $settings['news_types'], 'post_status' => 'publish', 'posts_per_page' => 1000, 'date_query' => array( array( 'after' => '48 hours ago' ) ), 'exclude' => $this->excluded(), ) ); $name = '' !== trim( (string) $settings['news_name'] ) ? (string) $settings['news_name'] : get_bloginfo( 'name' ); $lang = substr( (string) get_bloginfo( 'language' ), 0, 2 ); $xml = '' . "\n"; $xml .= '' . "\n"; foreach ( $posts as $post ) { if ( get_post_meta( $post->ID, '_airanksuite_exclude_sitemap', true ) ) { continue; } $xml .= "\t\n\t\t" . esc_url( (string) get_permalink( $post ) ) . "\n"; $xml .= "\t\t\n\t\t\t\n"; $xml .= "\t\t\t\t" . esc_html( $name ) . "\n"; $xml .= "\t\t\t\t" . esc_html( $lang ) . "\n"; $xml .= "\t\t\t\n"; $xml .= "\t\t\t" . esc_html( (string) get_post_time( 'c', true, $post ) ) . "\n"; $xml .= "\t\t\t" . esc_html( wp_strip_all_tags( get_the_title( $post ) ) ) . "\n"; $xml .= "\t\t\n\t\n"; } return $xml . ''; } /** * Video sitemap — pages carrying a detectable or manually set video. */ public function video(): string { $settings = $this->settings(); if ( empty( $settings['video_enabled'] ) ) { return ''; } $posts = get_posts( array( 'post_type' => (array) $settings['post_types'], 'post_status' => 'publish', 'posts_per_page' => 500, 'exclude' => $this->excluded(), ) ); $xml = '' . "\n"; $xml .= '' . "\n"; foreach ( $posts as $post ) { $stored = get_post_meta( $post->ID, '_airanksuite_schema_data', true ); $stored = is_array( $stored ) ? $stored : array(); $player = trim( (string) ( $stored['embed_url'] ?? '' ) ); if ( '' === $player ) { $player = (string) \AiRankSuite\Modules\Schema\Services\SchemaTypes::detect_video( $post ); } if ( '' === $player ) { continue; } $thumb = trim( (string) ( $stored['thumbnail'] ?? '' ) ); if ( '' === $thumb ) { $thumb = (string) get_the_post_thumbnail_url( $post, 'full' ); } if ( '' === $thumb ) { continue; // A thumbnail is required by the spec. } $description = wp_strip_all_tags( (string) ( get_post_meta( $post->ID, '_airanksuite_seo_desc', true ) ?: get_the_excerpt( $post ) ) ); $xml .= "\t\n\t\t" . esc_url( (string) get_permalink( $post ) ) . "\n"; $xml .= "\t\t\n"; $xml .= "\t\t\t" . esc_url( $thumb ) . "\n"; $xml .= "\t\t\t" . esc_html( wp_strip_all_tags( get_the_title( $post ) ) ) . "\n"; $xml .= "\t\t\t" . esc_html( '' !== $description ? $description : wp_strip_all_tags( get_the_title( $post ) ) ) . "\n"; $xml .= "\t\t\t" . esc_url( $player ) . "\n"; $xml .= "\t\t\t" . esc_html( (string) get_post_time( 'c', true, $post ) ) . "\n"; $xml .= "\t\t\n\t\n"; } return $xml . ''; } /** * Indexable posts of a type — counted exactly the way posts() filters them. * * wp_count_posts() counts every published post, including the ones set to * noindex, password-protected or excluded by id. Reporting that number as * "URLs in sitemap" is a small lie that becomes obvious the moment someone * opens the XML and counts, so the count runs the same query the file does. */ private function count_posts( string $type ): int { $query = new \WP_Query( array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => 1, 'fields' => 'ids', 'exclude' => $this->excluded(), 'has_password' => false, 'suppress_filters' => false, 'no_found_rows' => false, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query 'meta_query' => array( 'relation' => 'AND', array( 'relation' => 'OR', array( 'key' => '_airanksuite_robots', 'compare' => 'NOT EXISTS', ), array( 'key' => '_airanksuite_robots', 'value' => 'noindex', 'compare' => 'NOT LIKE', ), ), array( 'key' => '_airanksuite_exclude_sitemap', 'compare' => 'NOT EXISTS', ), ), ) ); return (int) $query->found_posts; } private function count_terms( string $taxonomy ): int { $count = wp_count_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => true ) ); return is_wp_error( $count ) ? 0 : (int) $count; } /** * Newest published post in each of these terms, in one query. * * @param array $term_ids * @return array term_id => ISO-8601 date. */ private function term_lastmods( array $term_ids ): array { $term_ids = array_values( array_filter( array_map( 'intval', $term_ids ) ) ); if ( array() === $term_ids ) { return array(); } global $wpdb; $placeholders = implode( ', ', array_fill( 0, count( $term_ids ), '%d' ) ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery $rows = $wpdb->get_results( $wpdb->prepare( "SELECT tt.term_id AS term_id, MAX(p.post_modified_gmt) AS modified FROM {$wpdb->term_taxonomy} tt JOIN {$wpdb->term_relationships} tr ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN {$wpdb->posts} p ON p.ID = tr.object_id WHERE tt.term_id IN ( {$placeholders} ) AND p.post_status = 'publish' GROUP BY tt.term_id", $term_ids ), ARRAY_A ); // phpcs:enable $out = array(); foreach ( (array) $rows as $row ) { $stamp = strtotime( (string) ( $row['modified'] ?? '' ) . ' UTC' ); if ( $stamp ) { $out[ (int) $row['term_id'] ] = gmdate( 'c', $stamp ); } } return $out; } /** Newest published post anywhere in a taxonomy — the index entry's date. */ private function latest_in_taxonomy( string $taxonomy ): string { global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery $modified = $wpdb->get_var( $wpdb->prepare( "SELECT MAX(p.post_modified_gmt) FROM {$wpdb->term_taxonomy} tt JOIN {$wpdb->term_relationships} tr ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN {$wpdb->posts} p ON p.ID = tr.object_id WHERE tt.taxonomy = %s AND p.post_status = 'publish'", $taxonomy ) ); // phpcs:enable $stamp = strtotime( (string) $modified . ' UTC' ); return $stamp ? gmdate( 'c', $stamp ) : ''; } private function latest_modified( string $type ): string { $posts = get_posts( array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => 1, 'orderby' => 'modified', 'order' => 'DESC', ) ); return empty( $posts ) ? '' : (string) get_post_modified_time( 'c', true, $posts[0] ); } /** * What is actually in the sitemap, broken down per file. * * "Is my sitemap right?" is answered by seeing the same list the index * emits, with counts — not by opening the XML and counting tags. * * @return array{files: array>, excluded: int} */ public function breakdown(): array { $settings = $this->settings(); $per_page = max( 1, (int) $settings['per_page'] ); $files = array(); foreach ( (array) $settings['post_types'] as $type ) { $object = get_post_type_object( $type ); $count = $this->count_posts( $type ); $pages = (int) ceil( $count / $per_page ); for ( $i = 1; $i <= $pages; $i++ ) { // The last file holds the remainder, not a full page. $in_file = ( $i === $pages ) ? $count - ( $pages - 1 ) * $per_page : $per_page; $files[] = array( 'kind' => 'post_type', 'label' => ( $object->labels->name ?? $type ) . ( $pages > 1 ? " ({$i}/{$pages})" : '' ), 'slug' => $type, 'url' => home_url( "/sitemap-{$type}-{$i}.xml" ), 'urls' => max( 0, $in_file ), 'lastmod' => $this->latest_modified( $type ), ); } if ( 0 === $pages ) { // Selected but empty: silence here reads as a broken sitemap. $files[] = array( 'kind' => 'post_type', 'label' => $object->labels->name ?? $type, 'slug' => $type, 'url' => '', 'urls' => 0, 'lastmod' => '', ); } } foreach ( (array) $settings['taxonomies'] as $tax ) { $object = get_taxonomy( $tax ); $count = $this->count_terms( $tax ); $files[] = array( 'kind' => 'taxonomy', 'label' => $object->labels->name ?? $tax, 'slug' => $tax, 'url' => $count > 0 ? home_url( "/sitemap-tax-{$tax}-1.xml" ) : '', 'urls' => $count, 'lastmod' => $count > 0 ? $this->latest_in_taxonomy( $tax ) : '', ); } if ( ! empty( $settings['news_enabled'] ) ) { $files[] = array( 'kind' => 'news', 'label' => __( 'Google News (last 48 hours)', 'ai-rank-suite' ), 'slug' => 'news', 'url' => home_url( '/news-sitemap.xml' ), 'urls' => null, 'lastmod' => '', ); } if ( ! empty( $settings['video_enabled'] ) ) { $files[] = array( 'kind' => 'video', 'label' => __( 'Video', 'ai-rank-suite' ), 'slug' => 'video', 'url' => home_url( '/video-sitemap.xml' ), 'urls' => null, 'lastmod' => '', ); } return array( 'files' => $files, 'excluded' => count( $this->excluded() ), ); } /** * Total indexable URLs (for the admin summary). */ public function total_urls(): int { $total = 0; foreach ( (array) $this->settings()['post_types'] as $type ) { $total += $this->count_posts( $type ); } foreach ( (array) $this->settings()['taxonomies'] as $tax ) { $total += $this->count_terms( $tax ); } return $total; } public static function flush_cache(): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", '_transient_' . self::CACHE_PREFIX . '%', '_transient_timeout_' . self::CACHE_PREFIX . '%' ) ); } }