Skip to:
Content
Pages
Categories
Search
Top
Bottom

WooCommerce – Hide content if user did not purchase product


  • Aron Prins
    Keymaster

    @aronprins

    Hey guys,

    Back in the day when running my sites, I always remembered struggling to hide content for members who did not purchase a certain product.

    Wether it’s a video, text, a link, or anything else, this shortcode function and example can help you hide content for WordPress users that are logged in but did not purchase the product you specified in the shortcode’s parameters.

    function hide_content_if_not_purchased( $atts, $content = null ) {
        // Parse shortcode attributes
        $atts = shortcode_atts( array(
            'product_id' => 0,
            'not_purchased_text' => 'You do not have access to this content.',
        ), $atts, 'hide_if_not_purchased' );
    
        // Get the current user
        $user = wp_get_current_user();
    
        // Check if the user has purchased the product
        $purchased = wc_customer_bought_product( $user->user_email, $user->ID, $atts['product_id'] );
    
        // If the user has purchased the product, show the content
        if ( $purchased ) {
            return do_shortcode( $content );
        }
    
        // If the user has not purchased the product, show the not purchased text
        return $atts['not_purchased_text'];
    }
    add_shortcode( 'hide_if_not_purchased', 'hide_content_if_not_purchased' );

    Add this function to your theme’s functions.php file, or in a custom plugin you are running on your WordPress setup.

    Then, to use the shortcode, simply copy the following example shortcode and place it wherever on your site you want to deliver your product’s content:

    [hide_if_not_purchased product_id="123" not_purchased_text="Sorry, this content is only available to customers who have purchased product 123."]This content will be hidden if the current user has not purchased product 123.[/hide_if_not_purchased]

    Make sure you set the right product_id value in the shortcode (you can find this on your wp admin’s products index page by hovering over the product and checking the ID) and adjusting the not_purchased_text parameter – hint: include a link to purchase the product there ;).

    Cheers,
    Aron

  • You must be logged in to reply to this topic.
Skip to toolbar