Add translated url to Rankmath sitemap index

First step, add this snippet to be sure to purge the sitemap caching

/**
 * Filter if XML sitemap transient cache is enabled.
 *
 * @param boolean $unsigned Enable cache or not, defaults to true
 */
add_filter( 'rank_math/sitemap/enable_caching', '__return_false');

Add this filter. For the moment you need to add the list of url you want to translate into your sitemap

add_filter( 'rank_math/sitemap/index', function( $xml ) {
	// Fetch Weglot services
	$language_services = weglot_get_service( 'Language_Service_Weglot' );
	$request_url_services = weglot_get_service( 'Request_Url_Service_Weglot' );

	// List of URLs to be translated
	$urls = [
		"http://beta-429.local/post-sitemap.xml",
		"http://beta-429.local/page-sitemap.xml",
		"http://beta-429.local/category-sitemap.xml",
	];

	$destination_languages = weglot_get_destination_languages();
	foreach ( $urls as $url ) {
		$wg_url = $request_url_services->create_url_object( $url );

		// Iterate over each destination language
		foreach ( $destination_languages as $language_code ) {
			$language = $language_services->get_language_from_internal( $language_code['language_to'] );

			$translated_url = $wg_url->getForLanguage( $language );

			$xml .= '
                <sitemap>
                    <loc>' . esc_url( $translated_url ) . '</loc>
                    <lastmod>' . esc_html( date( 'c' ) ) . '</lastmod>
                </sitemap>';
		}
	}

	return $xml;
}, 999 );

Last updated