Insert Values into a custom table once order is pl

2019-07-18 23:49发布

I need to insert into my custom table called license_table

 **username**, **order id**, **Quantity** 
 This needs to be populated when an order is placed. 
Username = customer's email id
 Quantity = quantity (of the product)
order id=Order ID

i have used but not working

add_action( 'woocommerce_order_status_completed', 'my_function' );
function my_function($order_id) {
    global $wpdb;
    $order = new WC_order($order_id);
    $customer_id= $order->id;
    $email= $order->billing_email;
    $email1= $order->id;
    $table_name =  "aitoe_license_table";
    $wpdb->insert( $table_name, array(
      'username' => $customer_id,
       'order_id' => $email,
       'number_of_cameras' => 12,
      'boolean' => 'False',
    ) );

   }

1条回答
疯言疯语
2楼-- · 2019-07-19 00:30

To really help you (and testing for real your code), you should provide the code that you are using to create your table (or the sql query) updating your question.

In your code there is strange things as 'order_id' => $email that should be the Order ID value and not the email… Also $customer_id= $order->id; that is NOT the ID of the customer user, but the Order ID, and $email1= $order->id; that is not used and it's wrong… */

<?php

#-------------------- code begins below -------------------------#

add_action( 'woocommerce_order_status_completed', 'my_function' );
function my_function($order_id) {
    global $wpdb;

    // Getting the order (object type)
    $order = wc_get_order( $order_id );

    // Getting order items
    $items = $order->get_items(); 
    $total_items_qty = 0;

    // Iterating through each item (here we do it on first only)
    foreach ( $items as $item ) {
        $total_items_qty += $item["qty"];
    }

    // Here are the correct way to get some values:
    $customer_id           = $order->customer_user;
    $billing_email         = $order->billing_email;
    $complete_billing_name = $order->billing_first_name . ' ' . $order->billing_last_name;

    // Getting the user data (if needed)
    $user_data             = get_userdata( $customer_id );
    $customer_login_name   = $user_data->user_login;
    $customer_login_email  = $user_data->user_email;

    // "$wpdb->prefix" will prepend your table prefix
    $table_name =  $wpdb->prefix."license_table";

    // This array is not correct (as explained above)
    $data = array( 
        'username'          => $customer_login_name,
        'order_id'          => $order_id,
        'number_of_cameras' => $total_items_qty,
        'boolean'           => 'false',
    );

    $wpdb->insert( $table_name, $data );

}

#-------------------- code end -------------------------#

?>

Also what is strange is that you can have many items (products) in an order and your table can't handle this, as you should need also a line by item…

查看更多
登录 后发表回答