skip to Main Content

I use WooCommerce with WordPress and I would like to update a custom field for the purchase of a single product at the time of payment validation with the display of the thank you page.

I started from this code but it does not work for the moment.

add_action( 'woocommerce_thankyou', 'checkout_update_user_meta' );
 
function checkout_update_user_meta( $order_id ) {
   $order = new WC_Order( '$order_id' );
   $user_id = $order->get_user_id();
   $items = $order->get_items();

foreach ( $items as $item ) {

$product_id = $item['product_id'];

if ( $product_id == '777' ) {    
      update_user_meta( $user_id, 'masterclass-1', 'ok' );
  }
}
}

2

Answers


  1. add_action( 'woocommerce_thankyou', 'checkout_update_user_meta' );
     
    function checkout_update_user_meta( $order_id ) {
       $order = new WC_Order( $order_id );
       $user_id = $order->get_user_id();
       $items = $order->get_items();
    
    foreach ( $items as $item ) {
    
    $product_id = $item['product_id'];
    
    if ( $product_id === 777 ) {    
          update_user_meta( $user_id, 'masterclass-1', 'ok' );
      }
    }
    }
    

    The issue with your code was that you wrapped the $order_id in single quotes. This line $order = new WC_Order( $order_id ); can also be replaced as $order = wc_get_order( $order_id );

    enter image description here

    Login or Signup to reply.
  2. I just modified your code to Update user meta field after woocommerce checkout according to your need. Please check my changes and hope it will work 👍

    add_action( 'woocommerce_thankyou', 'checkout_update_user_meta' );
     
    function checkout_update_user_meta( $order_id ) {
       $order = wc_get_order( $order_id );
       $user_id = $order->get_user_id();
       $items = $order->get_items();
    
    foreach ( $items as $item ) {
    
    $product_id = $item->get_product_id();
    
    if ( $product_id == 777 ) {    
          update_user_meta( $user_id, 'masterclass-1', 'ok' );
      }
    }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search