self::build_xml( array_merge( $posts, self::term_urls() ) ), 'post_urls' => count( $posts ), ); } /** * URL entries for every public post type's published posts whose * resolved policy includes them in the sitemap. * * @return array */ protected static function post_urls(): array { $include_images = self::include_images(); $urls = array(); foreach ( array_keys( ABDS_SEO_Taxonomy_Helper::public_post_types() ) as $post_type ) { $post_ids = get_posts( array( 'post_type' => $post_type, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ) ); foreach ( $post_ids as $post_id ) { $policy = ABDS_SEO_Policy_Engine::resolve( (int) $post_id ); if ( ! $policy['in_sitemap'] ) { continue; } $images = array(); if ( $include_images ) { $thumb = get_the_post_thumbnail_url( $post_id, 'full' ); if ( is_string( $thumb ) && '' !== $thumb ) { $images[] = $thumb; } } $urls[] = array( 'loc' => '' !== $policy['canonical'] ? $policy['canonical'] : (string) get_permalink( $post_id ), 'lastmod' => (string) get_post_modified_time( 'c', true, $post_id ), 'images' => $images, ); } } return $urls; } /** * URL entries for every public taxonomy's terms whose resolved policy * includes them in the sitemap. * * @return array */ protected static function term_urls(): array { $urls = array(); foreach ( array_keys( ABDS_SEO_Taxonomy_Helper::public_taxonomies() ) as $taxonomy ) { $terms = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => true, ) ); if ( is_wp_error( $terms ) ) { continue; } foreach ( $terms as $term ) { $policy = ABDS_SEO_Policy_Engine::resolve( $term ); if ( ! $policy['in_sitemap'] ) { continue; } $urls[] = array( 'loc' => '' !== $policy['canonical'] ? $policy['canonical'] : (string) get_term_link( $term ), 'lastmod' => '', 'images' => array(), ); } } return $urls; } /** * Whether the Sitemap tab's "include images" toggle is on. * * @return bool */ protected static function include_images(): bool { $settings = get_option( 'abds_seo_settings', array() ); return true === ( $settings['sitemap']['include_images'] ?? false ); } /** * Renders the gathered URL entries as a sitemap-protocol XML document. * * @param array $urls URL entries, see post_urls()/term_urls(). * @return string */ protected static function build_xml( array $urls ): string { $xml = '' . "\n"; $xml .= '' . "\n"; foreach ( $urls as $url ) { $xml .= "\t\n"; $xml .= "\t\t" . esc_url( $url['loc'] ) . "\n"; if ( '' !== $url['lastmod'] ) { $xml .= "\t\t" . esc_html( $url['lastmod'] ) . "\n"; } foreach ( $url['images'] as $image ) { $xml .= "\t\t" . esc_url( $image ) . "\n"; } $xml .= "\t\n"; } $xml .= ''; return $xml; } }