Skip to content

Commit e6e6e59

Browse files
committed
Add cache-control headers for archives and robots.txt
1 parent 7d1c9c5 commit e6e6e59

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

default-cache-control.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,3 +182,52 @@ function add_admin_notice() {
182182

183183
// Hook to add notice on admin pages
184184
\add_action( 'admin_notices', __NAMESPACE__ . '\\add_admin_notice' );
185+
186+
/**
187+
* Sends HTTP cache control headers for post type archives.
188+
*
189+
* This function checks if `cache_control_send_http_header` exists
190+
* and if the current page is a post type archive (`is_post_type_archive()`).
191+
* If both conditions are met, it removes its own hook to prevent duplicate execution
192+
* and sends cache headers based on the 'categories' option.
193+
*
194+
* @return void
195+
*/
196+
function cache_control_send_post_type_archive_headers() {
197+
if ( ! function_exists( 'cache_control_send_http_header' ) || ! is_post_type_archive() ) {
198+
return;
199+
}
200+
201+
remove_action( 'template_redirect', 'cache_control_send_headers' );
202+
203+
cache_control_send_http_header( cache_control_build_directive_from_option( 'categories' ) );
204+
}
205+
206+
\add_action( 'template_redirect', __NAMESPACE__ . '\\cache_control_send_post_type_archive_headers', 9 );
207+
208+
/**
209+
* Sends HTTP cache control headers for robots.txt.
210+
*
211+
* This function hooks into 'do_robots' action to send cache headers
212+
* Cache duration: 1 hour.
213+
*
214+
* @return void
215+
*/
216+
function cache_control_send_robots_headers() {
217+
// 1 hour cache for robots.txt
218+
$s_maxage = \HOUR_IN_SECONDS;
219+
220+
// Send cache headers directly
221+
header(
222+
sprintf(
223+
'Cache-Control: public, max-age=%d, s-maxage=%d, stale-while-revalidate=%d, stale-if-error=%d',
224+
$s_maxage,
225+
$s_maxage,
226+
$s_maxage * 5,
227+
$s_maxage * 3
228+
),
229+
true // Replace existing Cache-Control header
230+
);
231+
}
232+
233+
\add_action( 'do_robots', __NAMESPACE__ . '\\cache_control_send_robots_headers', 1 );

0 commit comments

Comments
 (0)