File: /var/www/dk/wp-content/themes/food/api/order/c_order.php
<?php
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
//echo 'c_order $current_id -> ' . $current_id . '<br>';
if ($current_id == 0) {
$rc = 1;
return false;
}
$param = [
'order_products' => true,
'cart_id' => false
];
$data_form = [];
foreach ($param as $key => $value) {
if ($value && !isset($_POST[$key])) {
$rc = 1;
return false;
} else {
$data_form[$key] = $_POST[$key];
}
}
$order_args = array(
'status' => null,
// 'customer_id' => 1,
'customer_id' => $current_id,
'parent' => null,
'created_via' => null,
'cart_hash' => null,
'customer_note' => "",
'order_id' => 0,
);
$address_key = get_user_meta($current_id, 'address_current', true);
if (in_array($address_key, ['address1', 'address1', 'address3', 'address4'])) {
$address_value = get_user_meta($current_id, $address_key, true);
} else {
$address_value = "";
}
$address = array(
'first_name' => $current_user->data->user_nicename,
'last_name' => $current_user->data->user_nicename,
'company' => " ",
'email' => get_user_meta($current_id, 'user_email', true),
'phone' => get_user_meta($current_id, 'user_phone', true),
'address_1' => $address_value,
'address_2' => " ",
'city' => " ",
'state' => " ",
'postcode' => " ",
'country' => " ",
);
$res = $address;
$order = wc_create_order($order_args);
foreach ($data_form['order_products'] as $a) {
$order->add_product(wc_get_product($a['product_id']), $a['product_num']);
}
$order->set_address($address, 'billing');
$order->set_address($address, 'shipping');
$order->calculate_totals();
if (!empty($_FILES['pay_file'])) {
//保存文件並保留備註
$uploadedfile = $_FILES['pay_file'];
$filename = basename($uploadedfile['name']);
$etx = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$attachment_id = media_handle_upload('pay_file', 0);
if (!is_wp_error($attachment_id)) {
$post = get_post($attachment_id);
$note = '<img style="width:100%" src="' . $post->guid . '">';
$order->add_order_note($note);
$order->update_status("processing");
} else {
$rc = 2;
$msg = 'upload fail';
$order->update_status("pending");
}
} else {
$order->update_status("pending");
}
// 修改購物車狀態
if (is_array($data_form['cart_id'])) {
foreach ($data_form['cart_id'] as $cart_id) {
$res = $wpdb->update('food_cart', [
'status' => 2
], [
'id' => $cart_id
]);
}
}