1

I have a website with few WooCommerce products, and the product page is created with Elementor Pro. I want users to be able to click Add to Cart and buy the product normally.

But then when the user goes back to the product page (after buying the product), they would not see the the Add to Cart button (if will be hidden for those that purchased the product) and they will see another extra section.

How can I do this?

I also have Crocoblock and JetEngine that have a Dynamic Visibility functionality built in Elementor.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40

1 Answers1

0

The easiest way to achieve this would be by creating a child theme. The child theme should contain 2 added functionalities. For this to fully work you will need all users to be registered and NOT have checkout as a guest enabled. Also, this will only work for new orders. If you want to add compatibility for old orders you'd have to create a script that sets the meta value for all users that have purchased this product before the code was implemented.

First of we create a function that adds metadata to the purchasing user account if the product was in the cart. Add the following code to your child theme functions.php

add_action( 'woocommerce_thankyou', 'custom_add_user_meta');
   
function custom_add_user_meta( $order_id ){
$user_id = get_current_user_id();
$order = wc_get_order( $order_id );
$items = $order->get_items(); 
   foreach ( $items as $item_id => $item ) {
      $product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
      if ( $product_id == 12345  ) {
         add_user_meta( $user_id, '_product_xyz_purchased', "true");
      }
   }
}

Now we add the following code to the same functions.php file to render additional content on the single product page of WooCommerce. NOTE: This step is for a more complete overview that can be implemented outside of Crocoblocks/Jetegine. The following step can be skipped because Jetengine allows setting conditions based on user_meta

add_action("woocommerce_after_single_product", 'render_additional_content', 50);

function render_additional_content() {
   $user_id = get_current_user_id();
   $product_purchased = get_user_meta( $user_id, '_product_xyz_purchased', true);
   if($product_purchased == "true"){
      echo "here you can put the HTML you want to display";
   }
}
Growdzen
  • 79
  • 4
  • Thank you for your reply! I get an error when I do what you described. "Cannot redeclare add_user_meta()" Please take a look: https://ibb.co/xs6BcsQ Can we fix this? – Aleksandar Simov Feb 26 '22 at 16:00
  • Because it is one of the core WP function. Use a different name while adding the hook and declaring the function. change this add_action( 'woocommerce_thankyou', 'add_user_meta'); to add_action( 'woocommerce_thankyou', 'add_user_meta_product_purchased'); – Vik Cheema Feb 26 '22 at 17:24