How to write a file from a theme to the “Site Address” directory?


I recently came across a theme which creates a sitemap and attempts to add it to the Site Address directory/root, so https://example.com/sitemap.xml. I believe the way this theme does it makes some bad assumptions about file paths and uses ABSPATH.

$  fp = fopen( ABSPATH . 'sitemap.xml', 'w' ); fwrite( $  fp, $  sitemap ); fclose( $  fp ); 

In most cases, this might work without incident. However, I’m actually using Bedrock which means sitemap.xml ends up in https://example.com/wp/sitemap.xml with /wp/ added and so visiting the expected URI (https://example.com/sitemap.xml) results in a 404.

I’d like to correct this via a child theme or by PR but I frankly have no clue where to begin, so I’ve currently just made some symlinks, but something tells me there’s a more thorough approach.