Search code examples
phpwordpresswoocommerceproducthook-woocommerce

Hide WooCommerce product if already purchased by logged in user


I am creating an LMS using LearnDash + WooCommerce. So far so good. Now, I'd like to hide a Product when the logged-in user has already purchased it to a) prevent the user from purchasing it twice, and b) so that I can display a product grid for them without the already purchased item(s).

Another example: if a user who purchased ITEM A goes to the shop, ITEM A should not even be displayed for them.

Thanks so much!


Solution

  • So, I ended up with a nice workaround:

    On the product page, I created a CUSTOM FIELD where I can input the COURSE ID.

    Then, with PHP, I check the Product and retrieve the custom field for the COURSE ID.

    LearnDash has a shortcode for students... so after retrieving the course ID, I can display a message/button for users who have registered already for this course.

    This is the code:

    <?php
        global $product;
        $postid = $product->get_id();
        $courseid = get_post_meta( $product->get_id(), 'ID_del_curso', true );
        $html = '"]<center><div class="alreadyPurchased"><i class="fas fa-graduation-cap paddingRightM"></i> Ya te has registrado</div></center>';
        $openIT = '[student course_id="';
        $closeIT = '[/student]';
        echo do_shortcode( $openIT . $courseid . $html . $closeIT ); 
    ?>
    

    Hope it helps!