Restrict Page Access Based on Purchased Products in WooCommerce

WooCommerce PHP July 23, 2026

This code restricts access to specific pages based on whether the logged-in customer has purchased at least one product from a defined list.

Guests are blocked with an access message.

Logged-in users must have purchased any one of the allowed product IDs for that page.

If not, a message with a return link is shown.

Add this code to your theme’s functions.php or a custom plugin.

✅ Easy to update: just modify the $pages_products array to add more pages or product IDs
add_action('template_redirect', function() {
    $page = get_permalink();
    $redirect_url = 'https://natureheal.co.uk/your-daily-guide/';
    $no_access_message = '<div style="padding:20px; text-align:center;">
        <h2>You don't have access to this page.</h2>
        <a href="'.$redirect_url.'" style="color:blue;">Go Back to Your Daily Guide</a>
    </div>';
    $pages_products = [
        'https://natureheal.co.uk/your-daily-guide/salt-water-cleanse/' => [1361, 1362, 1364, 1365, 1366],
        'https://natureheal.co.uk/your-daily-guide/castor-oil-pack/' => [1365, 1366],
        'https://natureheal.co.uk/your-daily-guide/gall-bladder-cleanse/' => [1365, 1366],
        'https://natureheal.co.uk/your-daily-guide/homemade-probiotics/' => [1366],
    ];
    foreach ($pages_products as $url => $product_ids) {
        if (trailingslashit($page) == trailingslashit($url)) {
            if (!is_user_logged_in()) {
                wp_die($no_access_message);
            }
            $user = wp_get_current_user();
            $has_bought = false;
            foreach ($product_ids as $product_id) {
                if (wc_customer_bought_product($user->user_email, $user->ID, $product_id)) {
                    $has_bought = true;
                    break;
                }
            }
            if (!$has_bought) {
                wp_die($no_access_message);
            }
            break;
        }
    }
});