May 1, 2024

Set Up WooCommerce Content Restriction behind Purchase with a Snippet

Play Video

In this tutorial, you will learn how to set up a WooCommerce content restriction behind a purchase with a snippet. This method allows you to create exclusive areas on your WordPress website, ensuring only those who have purchased certain products can access them.


Prerequisites

Please ensure you have the following installed and activated before continuing with this tutorial:


Why Use Code Snippets for WooCommerce Content Restriction?

The method of restricting WooCommerce content with code snippets offers several advantages over other approaches, such as using dedicated plugins or membership systems. Here’s why this method is beneficial:

  1. Simplicity and Control
    By using a code snippet, you maintain direct control over the content restriction logic. This approach is simple, as it requires minimal setup and allows for easy customization to meet specific requirements. You decide which pages to restrict, which products unlock access, and where users are redirected if they don’t meet the requirements.
  2. Lightweight and Efficient
    Code snippets don’t add significant overhead to your website. Unlike some full-featured plugins or membership systems that may impact site performance due to their complexity, code snippets offer a lightweight solution. This can help keep your site fast and responsive.
  3. Flexibility
    With code snippets, you’re not limited to the features of a specific plugin. You can adapt and extend the logic as needed to fit your unique use case. Whether you need to restrict one page or multiple pages based on different conditions, code snippets give you the flexibility to customize your setup.
  4. Reduced Dependency on Plugins
    Using code snippets minimizes reliance on third-party plugins. This reduces the risk of compatibility issues or plugin-related vulnerabilities. It also means you don’t need to manage additional plugin settings or deal with licensing and updates from multiple sources.
  5. Cost-Effective
    Many plugins that offer similar content restriction functionality come with premium features or subscription costs. Using code snippets eliminates the need to purchase additional plugins, making it a cost-effective solution for budget-conscious website owners.

Instructions for WooCommerce Content Restriction with a Snippet

  1. Navigate to Snippets > Add New to create a new snippet. Name the snippet appropriately, such as “WooCommerce Content Restriction”
  2. Copy the following code snippet and paste it into the code area:
    function restrict_page_access() {
        // Configuration
        $access_rules = [
            'course-1' => [
                'product_ids' => [183],
                'redirect'    => 'https://websquadron.s3-tastewp.com/shop',
            ],
            'course-2' => [
                'product_ids' => [183, 186],
                'redirect'    => 'https://websquadron.s3-tastewp.com/contact',
            ],
            'course-3' => [
                'product_ids' => [190, 191],
                'redirect'    => 'https://websquadron.s3-tastewp.com/home',
            ],
        ];
    
        // Get current user ID and check if the user is an administrator
        $user_id = get_current_user_id();
        $is_admin = current_user_can('administrator');
    
        // If user is an administrator, skip restriction checks
        if ($is_admin) {
            return;
        }
    
        // Get the current page
        $current_page = get_queried_object();
    
        // Ensure $current_page is a WP_Post object
        if (!($current_page instanceof WP_Post)) {
            return;
        }
    
        // Iterate through access rules and apply restrictions
        foreach ($access_rules as $slug => $rule) {
            if ($current_page->post_name === $slug) {
                // Check if user has purchased any of the required products
                $has_purchased = false;
                foreach ($rule['product_ids'] as $product_id) {
                    if (wc_customer_bought_product($user_id, $user_id, $product_id)) {
                        $has_purchased = true;
                        break;
                    }
                }
    
                // Redirect if the user hasn't purchased the required products
                if (!$has_purchased) {
                    wp_redirect($rule['redirect']);
                    exit;
                }
            }
        }
    }
    add_action('template_redirect', 'restrict_page_access');

    Source: Code Snippets Cloud

    Copy the following code snippet and paste it into the code area WooCommerce

  3. Navigate to Products > All Products and find the WooCommerce products ID by hovering over the product name (example: 183, 186).
    Navigate to Products All Products and find the WooCommerce products ID by hovering over the product name
  4. Navigate to Pages > All Pages and locate the desired pages to identify their slugs (example: “course-one”, “course-two”).
  5. Replace the IDs within the code of the copied & pasted snippet accordingly. Save and activate the snippet.
    Replace the IDs within the code of the copied & pasted snippet accordingly

Official Documentation


WooCommerce Content Restriction – Conclusion

Using this method, you can easily restrict content in WooCommerce with a code snippet, allowing only authorized users to access certain pages. This can be applied to a variety of scenarios, from courses to premium resources or exclusive offers.

 

Required Resources

WooCommerce Logo
Free Options
Code Snippets Logo
Free Options
Credit to Web Squadron
Web Squadron is a popular YouTube channel dedicated to providing informative tutorials, tips, and insights on web development and design. With a strong focus on WordPress and website builders like Bricks Builder, the channel aims to help users of all skill levels, from beginners to advanced developers, create and optimize their websites. By offering easy-to-understand, step-by-step guidance, Web Squadron provides practical and valuable content.
Visit
Set Up WooCommerce Content Restriction behind Purchase with a Snippet
Welcome back!
Enter your Helwp credentials to sign in.

No Account yet? Sign Up

My Account
Menu
Give Feedback
Describe your feedback *
Rate Helwp
Share
Facebook
Twitter
LinkedIn
Reddit
Email
WhatsApp
Telegram
Pocket
Report
Problem *
Describe the problem
Want us to reply?
Your E-Mail
Affiliate Disclosure

At Helwp, we’re committed to transparency and honesty. Therefore, we want to inform you that some of the links on our website are affiliate links. This means that, at no additional cost to you, we may earn a small commission if you click through and make a purchase.

We only promote products or services that we genuinely believe in. These affiliate commissions help us to maintain the website and continue to provide you with free, high-quality WordPress content.

If you are interested in how you can support us even further, check out our support page.