woocommerce – pass the product if into custom function while adding an action

I am trying to add an action for the woocommerce hook woocommerce_add_cart_item_data and here I am trying to get the product id in the custom function I am using to hook. For this I have used get_the_ID() inside the function but it is not working. Is there any way to pass the woocommerce product id into my custom function while doing add_action?

My Code:

add_action('woocommerce_add_cart_item_data', 'order_session_date');

function order_session_date() {
   global $woocommerce;
   $product_id = get_the_ID();
   $sched_val = get_post_meta($product_id, '_sched_val', true);
   $data = array(
       $data_dates = $sched_val
   );
   WC()->session->set('name_for_your_data', $data);
}

Related posts

Leave a Reply

1 comment

  1. its a filter, the second parameter is the the id, make sure you return the first argument.

    add_filter('woocommerce_add_cart_item_data', 'order_session_date', 10, 2);
    
    function order_session_date( $data, $id) {
       global $woocommerce;
       $product_id = $id;
       $sched_val = get_post_meta($product_id, '_sched_val', true);
       $data = array(
           $data_dates = $sched_val
       );
       WC()->session->set('name_for_your_data', $data);
    
       return $data;
    }