Protect wp-cron.php From Outside Requests
Requires a secret key for requests to wp-cron.php and adds that key automatically to WordPress's own cron calls, so outsiders cannot hammer the endpoint to slow your site down.
Opens WPIDE on
Code
$wpide_cron_key = function () {
return substr( wp_hash( 'wpide-cron-key' ), 0, 20 );
};
add_filter( 'cron_request', function ( $request ) use ( $wpide_cron_key ) {
$request['url'] = add_query_arg( 'wpide_cron_key', $wpide_cron_key(), $request['url'] );
return $request;
} );
add_action( 'init', function () use ( $wpide_cron_key ) {
if ( ! wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
$script = isset( $_SERVER['SCRIPT_NAME'] ) ? basename( sanitize_text_field( wp_unslash( $_SERVER['SCRIPT_NAME'] ) ) ) : '';
$key = isset( $_GET['wpide_cron_key'] ) ? sanitize_text_field( wp_unslash( $_GET['wpide_cron_key'] ) ) : '';
if ( 'wp-cron.php' === $script && ! hash_equals( $wpide_cron_key(), $key ) ) {
status_header( 403 );
exit;
}
}, 0 );
add_filter( 'debug_information', function ( $info ) use ( $wpide_cron_key ) {
$info['wpide-cron'] = array(
'label' => 'WPIDE cron key',
'fields' => array(
'url' => array( 'label' => 'Cron URL for server cron jobs', 'value' => add_query_arg( 'wpide_cron_key', $wpide_cron_key(), site_url( 'wp-cron.php' ) ), 'private' => true ),
),
);
return $info;
} );
Notes
If a server cron job calls wp-cron.php, add ?wpide_cron_key=YOUR_KEY to its URL; the key is shown under Tools > Site Health > Info > WPIDE cron key.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.