Automaticly add “Multiple Pages Generator” Project sitemap to Yoast sitemap index

When using Multiple Page Generator for vastgoedopkoop.nl I didn’t want to relay on delivering the project Sitemap XML via the robots.txt. Therefore I wrote a filter to automaticly add them to the Yoast WordPress SEO sitemap_index.xml.

add_filter( 'wpseo_sitemap_index', function ( $sitemap_index ) {
	global $wpseo_sitemaps, $wpdb;

	// Unfortunatly no API / helper function for getting all projects
	$projects = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}" . \MPG_Constant::MPG_PROJECTS_TABLE);
	$project_ids = wp_list_pluck( $projects, 'id' );
	foreach( $project_ids as $project_id ) {

		$project = \MPG_ProjectModel::mpg_get_project_by_id( $project_id );
		if ( ! isset($project[0]) && empty( $project[0]->sitemap_filename ) ) {
			throw new Exception(__('Your project has not properly configured source file', 'mpg'));
		}

		$sitemap_index .= "<sitemap>
			<loc>" . htmlspecialchars( $project[0]->sitemap_url, ENT_COMPAT, $wpseo_sitemaps->renderer->get_output_charset(), false ) ."</loc>
			<lastmod>" . htmlspecialchars( YoastSEO()->helpers->date->format_timestamp( $project[0]->updated_at ), ENT_COMPAT, $wpseo_sitemaps->renderer->get_output_charset(), false ) . "</lastmod>
		</sitemap>";

	}
 
	return $sitemap_index;
 } );

Easy as that, enjoy and have fun!