To restrict access to specific pages on your WordPress site until a WooCommerce product is purchased, you can use the Code Snippets plugin. This tutorial will walk you through the process of setting up this restriction, ensuring that only those who have made a purchase can access certain content.
Prerequisites
Please make sure you have the following installed and activated:
- WooCommerce (Plugin)
- Code Snippets (Plugin)
Identifying Product and Page IDs
- Find the Product ID
Hover over your WooCommerce product in the dashboard to find the product ID. Note it down. - Get the Page Slug
Navigate to the page you want to restrict and click on ‘Quick Edit’ to find the slug. Note this down as well.
Creating a New Snippet
- Navigate to
Snippets > Add New
and name it “Restrict Pages with WooCommerce”. - Copy the Code:
function restrict_page_access() { // Get the current user ID $user_id = get_current_user_id(); // Check if the user is an administrator $is_admin = current_user_can('administrator'); // Check if the user has purchased the WooCommerce product with ID 297 $has_purchased_297 = wc_customer_bought_product($user_id, $user_id, 297); // Get the current page $current_page = get_queried_object(); // Check if the current page is "layout" and the user is not an administrator if ($current_page->post_name === 'layout' && !$has_purchased_297 && !$is_admin) { // Redirect the user to a specific URL wp_redirect('https://website.websquadron.co.uk/shop'); exit; } // Check if the current page is "test" and the user is not an administrator if ($current_page->post_name === 'test' && !$is_admin) { // Check if the user has purchased the WooCommerce product with ID 298 $has_purchased_298 = wc_customer_bought_product($user_id, $user_id, 298); // Check if the user has purchased either product 297 or 298 if (!($has_purchased_297 || $has_purchased_298)) { // Redirect the user to a specific URL wp_redirect('https://website.websquadron.co.uk/shop'); exit; } } } add_action('template_redirect', 'restrict_page_access');
Source: Code Snippets
- Modify the Code
Replace the placeholder IDs and slugs in the code with the ones you noted down earlier.
Additional Products and Pages
If you want to restrict multiple products or pages, you can extend the code snippet to include additional IDs and slugs.
Restrict Pages with WooCommerce Product Purchase – Conclusion
Restricting page access based on WooCommerce product purchases is a straightforward process with the Code Snippets plugin. By following these steps, you can easily set up a system where only verified purchasers can access specific content.