Search code examples
phpwordpresswoocommercehook-woocommerceorders

Set some WooCommerce Order and Order item data in a custom array


I’m trying to implement sending notifications in telegram in functions.php my theme…

All data is sent except product details, here is the code:

add_action( 'woocommerce_new_order', 'telegram_notification',  1, 1  );
function telegram_notification( $order_id ) {

            $order = wc_get_order( $order_id );
        $order_data = $order->get_data(); // The Order data 
        
        
$order_id = $order_data['id'];
$order_payment_method_title = $order_data['payment_method_title'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

$order_currency = $order_data['currency'];
$order_shipping_method = $order_data['shipping_method'];

$order_total = $order_data['total'];

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

   // data to send to third party
$product_name = '';
$product_sku = '';

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();  
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;
        

//Далее создаем переменную, в которую помещаем PHP массив
$arr = array(
  'Номер заказа: ' => $order_id,
  'Дата: ' => $order_date_modified,
  'Название товара: ' => $product_name,
  'Артикул: ' => $product_sku,
  'Мета продукта:' => $somemeta,
  'Цена товара: ' => $order_total,
  'Валюта: ' => $order_currency,
  'Имя: ' => $order_billing_first_name,
  'Фамилия: ' => $order_billing_last_name,
  'Телефон: ' => $order_billing_phone,
  'Email: ' => $order_billing_email,
  'Страна: ' => $order_billing_country,
  'Область: ' => $order_billing_state,
  'Город: ' => $order_billing_city,
  'Адрес1: ' => $order_billing_address_1,
  'Адрес2: ' => $order_billing_address_2,
  'Индекс: ' => $order_billing_postcode,
  'Метод доставки: ' => $order_shipping_method,
  'Метод оплаты: ' => $order_payment_method_title
);

//При помощи цикла перебираем массив и помещаем переменную $txt текст из массива $arr
foreach($arr as $key => $value) {
  $txt .= "<b>".$key."</b> ".$value."%0A";
};

and send to privat chat.

What am I doing wrong?

As I understand it, it just doesn't work to get data from foreach into $ arr.

I'm not good at programming, so I ask for help to figure it out.


Solution

  • Updated

    You can have many order items in an Order, but as it seem you need to get only the first order item use the following instead:

    add_action( 'woocommerce_new_order', 'telegram_notification',  1, 1  );
    function telegram_notification( $order_id ) {
        $order = wc_get_order( $order_id ); // Get the WC_Order Object
    
        $order_items = $order->get_items(); // Get order items array
    
        $order_item  = reset($order_items); // Keep the first order item
        
        $product     = $order_item->get_product(); // Get the WC_Product Object
    
        $somemeta    = ''; // <== To be defined !!!
        $txt         = ''; // Initializing
    
        // Add all order related data to our custom indexed array
        $arr = array(
            'Номер заказа: '    => $order_id,
            'Дата: '            => $order->get_date_modified()->date('Y-m-d H:i:s'),
            'Название товара: ' => $order_item->get_name(),
            'Артикул: '         => $product->get_sku(),
            'Мета продукта:'    => $somemeta, // ! Not defined
            'Цена товара: '     => $order->get_total(),
            'Валюта: '          => $order->get_currency(),
            'Имя: '             => $order->get_billing_first_name(),
            'Фамилия: '         => $order->get_billing_last_name(),
            'Телефон: '         => $order->get_billing_phone(),
            'Email: '           => $order->get_billing_email(),
            'Страна: '          => $order->get_billing_country(),
            'Область: '         => $order->get_billing_state(),
            'Город: '           => $order->get_billing_city(),
            'Адрес1: '          => $order->get_billing_address_1(),
            'Адрес2: '          => $order->get_billing_address_2(),
            'Индекс: '          => $order->get_billing_postcode(),
            'Метод доставки: '  => $order->get_shipping_method(),
            'Метод оплаты: '    => $order->get_payment_method_title() // Updated
        );
    
        // Loop through the data array to convert it as a string to be sent by SMS
        foreach($arr as $key => $value) {
            $txt .= "<b>".$key."</b> ".$value."%0A";
        };
    
        // Other code to send The SMS from $txt string variable
    }
    

    Tested and works…

    Related: