<?php

function cwpai_custom_wp_die_handler( $message, $title = '', $args = array() ) {
    // Define the page ID where users will be redirected
    $redirect_page_id = 2;

    // Check if the message is about the download limit
    if ( strpos( $message, 'Sorry, you have reached your download limit for this file' ) !== false ) {
        // Check if the redirect page exists and is published
        $redirect_page = get_post( $redirect_page_id );
        if ( $redirect_page && $redirect_page->post_status == 'publish' ) {
            wp_redirect( get_permalink( $redirect_page_id ) );
            exit;
        } else {
            // Redirect page is not valid, show a default error message
            echo 'The page you are trying to access is not available. Please contact support.';
            exit;
        }
    }

    // Default behavior for other cases
    _default_wp_die_handler( $message, $title, $args );
}

add_filter( 'wp_die_handler', function() { return 'cwpai_custom_wp_die_handler'; } );