1

I need to set the Cache-Control: no-cache, no-store, must-revalidate only for 301 redirects with function:

function cache_control_handle_redirects() {

    if ( $status == 301          ||          $status == 308 ) {



     header ( "Cache-Control: no-cache, no-store, must-revalidate" );


}

}
add_filter( 'wp_redirect_status', 'cache_control_handle_redirects', 10, 2 );

Does wp_redirect_status can handle Cache-Control header as well?

1
  • 301 and 308 are for permanent redirects. Not wanting to cache them implies they are not permanent, no? Commented Mar 19, 2018 at 15:29

1 Answer 1

4

You first problem is that $status is not coming from anywhere. In a filter you need to accept arguments in your callback function. If the number of arguments you're accepting is greater than 1 then you also need to specify that number as the 4th argument to add_filter().

You also need to return that value or the modified value. In this case if you don't do that then you're removing the status code from all redirects.

With these issues corrected your code will look like this:

function cache_control_handle_redirects( $status, $location ) {
    if ( $status == 301 || $status == 308 ) {
        header ( "Cache-Control: no-cache, no-store, must-revalidate" );
    }

    return $status;
}
add_filter( 'wp_redirect_status', 'cache_control_handle_redirects', 10, 2 );

That should do what you want.

There is a conceptual issue with this, in that filters should probably only be used for modifying values and not performing actions like this. That said, I don't see any alternatives other than plugging the wp_redirect() function to incorporate this functionality and it should work regardless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.