Last active
January 24, 2024 00:04
-
-
Save seanlanglands/a0cb0687c266a8e530c4fcb0d7fce0d9 to your computer and use it in GitHub Desktop.
Yoast SEO sitemap performance mitigations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Yoast sitemap performance improvements. | |
/** | |
* Objects are cached for 24 hours and changes will be applied upon next sitemap update. | |
*/ | |
add_filter( 'wpseo_enable_xml_sitemap_transient_caching', '__return_true' ); | |
add_action( 'parse_request', 'filter_yoast_sitemap_cache_maxage' ); | |
add_action( 'parse_request', 'block_query_string_sitemap_requests' ); | |
/** | |
* Hooks the parse_request action to insert cache control max-age headers for sitemaps. | |
* | |
* @param \WP $wp The WP object, passed by reference | |
*/ | |
function filter_yoast_sitemap_cache_maxage( WP $wp ): void { | |
if ( str_starts_with( $wp->matched_query, 'sitemap' ) ) { | |
header( 'Cache-Control: max-age=' . ( 12 * HOUR_IN_SECONDS ) ); | |
} | |
} | |
/** | |
* Block /sitemap requests if there's a query string. Prevent | |
* expensive queries resulting from an origin hit from a bad actor | |
* with a cache-busting string. | |
* | |
* @param \WP $wp The WP object, passed by reference | |
*/ | |
function block_query_string_sitemap_requests( WP $wp ): void { | |
if ( | |
str_starts_with( $wp->matched_query, 'sitemap' ) | |
&& ( ! empty( $_SERVER['QUERY_STRING'] ) ) | |
) { | |
header( 'HTTP/1.1 403 Forbidden' ); | |
exit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment