Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.