80 lines
2.4 KiB
PHP
80 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace Smilia\Core;
|
|
|
|
use WP_Post;
|
|
use WP_Sitemaps;
|
|
|
|
defined( 'ABSPATH' ) || exit;
|
|
|
|
final class Sitemap {
|
|
|
|
public function register(): void {
|
|
add_filter( 'wp_sitemaps_enabled', '__return_true' );
|
|
add_filter( 'wp_sitemaps_add_provider', array( $this, 'provider' ), 10, 2 );
|
|
add_filter( 'wp_sitemaps_post_types', array( $this, 'post_types' ) );
|
|
add_filter( 'wp_sitemaps_posts_query_args', array( $this, 'query_args' ), 10, 2 );
|
|
add_filter( 'wp_sitemaps_posts_entry', array( $this, 'entry' ), 10, 2 );
|
|
add_action( 'wp_sitemaps_init', array( $this, 'renderer' ) );
|
|
}
|
|
|
|
public function provider( $provider, string $name ) {
|
|
return 'posts' === $name ? $provider : false;
|
|
}
|
|
|
|
public function post_types( array $post_types ): array {
|
|
unset( $post_types['post'] );
|
|
return $post_types;
|
|
}
|
|
|
|
public function query_args( array $args, string $post_type ): array {
|
|
if ( 'page' !== $post_type ) {
|
|
return $args;
|
|
}
|
|
$hidden = get_posts(
|
|
array(
|
|
'post_type' => 'page',
|
|
'post_name__in' => Seo::SERVICE_PAGES,
|
|
'post_status' => 'publish',
|
|
'fields' => 'ids',
|
|
'posts_per_page' => -1,
|
|
'lang' => '',
|
|
)
|
|
);
|
|
if ( $hidden ) {
|
|
$args['post__not_in'] = array_merge( (array) ( $args['post__not_in'] ?? array() ), $hidden );
|
|
}
|
|
return $args;
|
|
}
|
|
|
|
public function entry( array $entry, WP_Post $post ): array {
|
|
if ( ! function_exists( 'pll_get_post_translations' ) || ! function_exists( 'pll_get_post_language' ) ) {
|
|
return $entry;
|
|
}
|
|
$links = array();
|
|
foreach ( (array) pll_get_post_translations( $post->ID ) as $id ) {
|
|
if ( 'publish' !== get_post_status( (int) $id ) ) {
|
|
continue;
|
|
}
|
|
$links[ (string) pll_get_post_language( (int) $id, 'slug' ) ] = (string) get_permalink( (int) $id );
|
|
}
|
|
if ( count( $links ) < 2 ) {
|
|
return $entry;
|
|
}
|
|
if ( function_exists( 'pll_languages_list' ) ) {
|
|
$order = array_flip( (array) pll_languages_list( array( 'fields' => 'slug' ) ) );
|
|
uksort( $links, static fn( string $a, string $b ): int => ( $order[ $a ] ?? PHP_INT_MAX ) <=> ( $order[ $b ] ?? PHP_INT_MAX ) );
|
|
}
|
|
$default = function_exists( 'pll_default_language' ) ? (string) pll_default_language( 'slug' ) : '';
|
|
if ( isset( $links[ $default ] ) ) {
|
|
$links['x-default'] = $links[ $default ];
|
|
}
|
|
$entry['alternates'] = $links;
|
|
return $entry;
|
|
}
|
|
|
|
public function renderer( WP_Sitemaps $sitemaps ): void {
|
|
$sitemaps->renderer = new Sitemap_Renderer();
|
|
}
|
|
}
|