Woocommerce 3+에서 라인 항목을 사용하여 프로그래밍 방식으로 주문 작성
프로그램적으로 Woocommerce 주문을 작성해야 했는데, '오래된' Woocommerce를 사용하는 것은 매우 더러운 절차가 되었습니다.
많은 update_post_meta 콜을 사용하여 모든 종류의 데이터베이스 레코드를 수동으로 삽입해야 했습니다.
더 나은 해결책을 찾고 있습니다.
최신 버전의 WooCommerce를 사용할 수 있으므로 다음과 같이 시도해 보십시오.
$address = array(
'first_name' => 'Fresher',
'last_name' => 'StAcK OvErFloW',
'company' => 'stackoverflow',
'email' => 'test@test.com',
'phone' => '777-777-777-777',
'address_1' => '31 Main Street',
'address_2' => '',
'city' => 'Chennai',
'state' => 'TN',
'postcode' => '12345',
'country' => 'IN'
);
$order = wc_create_order();
$order->add_product( get_product( '12' ), 2 ); //(get_product with id and next is for quantity)
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->add_coupon('Fresher','10','2'); // accepted param $couponcode, $couponamount,$coupon_tax
$order->calculate_totals();
위의 코드를 당신의 함수와 함께 호출하면 그에 따라 작동합니다.
2.1.12와 같은 이전 버전의 WooCommerce에서는 동작하지 않습니다.WooCommerce 2.2에서만 동작합니다.
도움이 되었으면 좋겠다
2017-2021 WooCommerce 3 이상용
Woocommerce 3에서는 CRUD 오브젝트가 도입되어 주문 아이템이 많이 변경되었습니다.또한 일부WC_Order현재는 다음과 같이 권장되지 않습니다.add_coupon().
다음은 세금 등 필요한 모든 데이터가 포함된 주문을 프로그래밍 방식으로 작성할 수 있는 기능입니다.
function create_wc_order( $data ){
$gateways = WC()->payment_gateways->get_available_payment_gateways();
$order = new WC_Order();
// Set Billing and Shipping adresses
foreach( array('billing_', 'shipping_') as $type ) {
foreach ( $data['address'] as $key => $value ) {
if( $type === 'shipping_' && in_array( $key, array( 'email', 'phone' ) ) )
continue;
$type_key = $type.$key;
if ( is_callable( array( $order, "set_{$type_key}" ) ) ) {
$order->{"set_{$type_key}"}( $value );
}
}
}
// Set other details
$order->set_created_via( 'programatically' );
$order->set_customer_id( $data['user_id'] );
$order->set_currency( get_woocommerce_currency() );
$order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) );
$order->set_customer_note( isset( $data['order_comments'] ) ? $data['order_comments'] : '' );
$order->set_payment_method( isset( $gateways[ $data['payment_method'] ] ) ? $gateways[ $data['payment_method'] ] : $data['payment_method'] );
$calculate_taxes_for = array(
'country' => $data['address']['country'],
'state' => $data['address']['state'],
'postcode' => $data['address']['postcode'],
'city' => $data['address']['city']
);
// Line items
foreach( $data['line_items'] as $line_item ) {
$args = $line_item['args'];
$product = wc_get_product( isset($args['variation_id']) && $args['variation_id'] > 0 ? $$args['variation_id'] : $args['product_id'] );
$item_id = $order->add_product( $product, $line_item['quantity'], $line_item['args'] );
$item = $order->get_item( $item_id, false );
$item->calculate_taxes($calculate_taxes_for);
$item->save();
}
// Coupon items
if( isset($data['coupon_items'])){
foreach( $data['coupon_items'] as $coupon_item ) {
$order->apply_coupon(sanitize_title($coupon_item['code']));
}
}
// Fee items
if( isset($data['fee_items'])){
foreach( $data['fee_items'] as $fee_item ) {
$item = new WC_Order_Item_Fee();
$item->set_name( $fee_item['name'] );
$item->set_total( $fee_item['total'] );
$tax_class = isset($fee_item['tax_class']) && $fee_item['tax_class'] != 0 ? $fee_item['tax_class'] : 0;
$item->set_tax_class( $tax_class ); // O if not taxable
$item->calculate_taxes($calculate_taxes_for);
$item->save();
$order->add_item( $item );
}
}
// Set calculated totals
$order->calculate_totals();
if( isset($data['order_status']) ) {
// Update order status from pending to your defined status and save data
$order->update_status($data['order_status']['status'], $data['order_status']['note']);
$order_id = $order->get_id();
} else {
// Save order to database (returns the order ID)
$order_id = $order->save();
}
// Returns the order ID
return $order_id;
}
코드가 기능합니다.php 파일 또는 플러그인 파일에 있는 활성 하위 테마(또는 활성 테마)입니다.
데이터 어레이에서의 사용 예:
create_wc_order( array(
'address' => array(
'first_name' => 'Fresher',
'last_name' => 'StAcK OvErFloW',
'company' => 'stackoverflow',
'email' => 'test1@testoo.com',
'phone' => '777-777-777-777',
'address_1' => '31 Main Street',
'address_2' => '',
'city' => 'Chennai',
'state' => 'TN',
'postcode' => '12345',
'country' => 'IN',
),
'user_id' => '',
'order_comments' => '',
'payment_method' => 'bacs',
'order_status' => array(
'status' => 'on-hold',
'note' => '',
),
'line_items' => array(
array(
'quantity' => 1,
'args' => array(
'product_id' => 37,
'variation_id' => '',
'variation' => array(),
)
),
),
'coupon_items' => array(
array(
'code' => 'summer',
),
),
'fee_items' => array(
array(
'name' => 'Delivery',
'total' => 5,
'tax_class' => 0, // Not taxable
),
),
) );
WC 2의 새로운 출시와 함께, 그것은 훨씬 더 좋아졌다.
단,
- 저는 제 WP 플러그인에서 직접 콜을 하기 때문에 REST API를 사용하고 싶지 않습니다.로컬 호스트에게 컬을 해도 소용없을 것 같아요.
- 'WooCommerce REST API Client Library'는 REST API에 릴레이되어 있고 주문 작성 호출을 지원하지 않으므로 유용하지 않습니다.
솔직히 말하면, WooCom의 API Docs는 한정되어 있기 때문에 아직 업데이트 중입니다.현재 신규 주문 작성 방법, 필요한 파라미터 등을 알려주지 않고 있습니다.
어쨌든 REST API에서 사용하는 클래스나 함수를 사용하여 라인 오더(상품)로 주문을 작성하는 방법을 알게 되어 공유하게 되었습니다!
저는 제 PHP 클래스를 만들었습니다.
class WP_MyPlugin_woocommerce
{
public static function init()
{
// required classes to create an order
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-exception.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-server.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-resource.php';
require_once WOOCOMMERCE_API_DIR . 'interface-wc-api-handler.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-json-handler.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-orders.php';
}
public static function create_order()
{
global $wp;
// create order
$server = new WC_API_Server( $wp->query_vars['wc-api-route'] );
$order = new WC_API_Orders( $server );
$order_id = $order->create_order( array
(
'order' => array
(
'status' => 'processing'
, 'customer_id' => get_current_user_id()
// , 'order_meta' => array
// (
// 'some order meta' => 'a value
// , some more order meta' => 1
// )
, 'shipping_address' => array
(
'first_name' => $firstname
, 'last_name' => $lastname
, 'address_1' => $address
, 'address_2' => $address2
, 'city' => $city
, 'postcode' => $postcode
, 'state' => $state
, 'country' => $country
)
, 'billing_address' => array(..can be same as shipping )
, 'line_items' => array
(
array
(
'product_id' => 258
, 'quantity' => 1
)
)
)
) );
var_dump($order_id);
die();
}
}
중요:
- 'WOOCOMMERCE_API_DIR' 상수는 플러그인 dir의 '/woocommerce/includes/api/'를 가리킵니다.
주문은 고객에게 할당되어 있습니다.이 경우는 현재 로그인하고 있는 유저입니다.사용자에게 주문 읽기, 편집, 작성 및 삭제 기능이 있는 역할이 있는지 확인합니다.제 역할은 다음과 같습니다.
$result = add_role( 'customer' , __( 'Customer' ) , array ( 'read' => true // , 'read_private_posts' => true // , 'read_private_products' => true , 'read_private_shop_orders' => true , 'edit_private_shop_orders' => true , 'delete_private_shop_orders' => true , 'publish_shop_orders' => true // , 'read_private_shop_coupons' => true , 'edit_posts' => false , 'delete_posts' => false , 'show_admin_bar_front' => false ) );점장의 권한을 보려면 체크하세요.
var_syslog(get_option('wp_user_syslog'));
create_order 함수는 order_items 테이블에 있는 줄 항목을 사용하여 주문을 작성합니다.
내가 널 도와줬길 바래, 제대로 하는데 시간이 좀 걸렸어.
많은 답변이 사용하기에 가장 적합한 필터(훅)를 보여줍니다.'init'을 사용하면 주문이 계속 늘어나서 며칠 동안 검색해 봤습니다.2분만에 나는 30개의 주문을 받았다.어쨌든 이 코드를 사용하면 1개의 주문이 작성됩니다.또한 $product = wc_get_product('1001')를 제품 ID로 변경합니다.참고 자료는 144행 https://github.com/dipolukarov/wordpress/blob/master/wp-content/plugins/woocommerce/classes/class-wc-checkout.php에 있습니다.
function my_init2() {
$order = wc_create_order();
$order_id = $order->get_id();
$product = wc_get_product( '10001' );
$address = array(
'first_name' => 'John2',
'last_name' => 'Smith1',
'email' => 'johnsmith1@gmail.com',
);
//$order->date_created(2020-07-21 );
$order->add_product( $product, 1 );
$order->set_address( $address, 'billing' );
$order->set_created_via( 'programatically' );
$order->calculate_totals();
$order->set_total( $product->get_price() );
$order->update_status( 'wc-completed' );
error_log( '$order_id: ' . $order_id );
}
//add_action('admin_init','my_init2');
function my_run_only_once() {
if ( get_option( 'my_run_only_once_20' ) != 'completed' ) {
my_init2();
update_option( 'my_run_only_once_20', 'completed' );
}
}
add_action( 'admin_init', 'my_run_only_once' );
언급URL : https://stackoverflow.com/questions/26581467/create-an-order-programmatically-with-line-items-in-woocommerce-3
'codememo' 카테고리의 다른 글
| 각도 UI 라우터가 비동기 데이터를 해상도로 가져옵니다. (0) | 2023.02.16 |
|---|---|
| Android에서 json 생성 (0) | 2023.02.16 |
| URL 패턴에 따라 스프링 부트필터를 적용하는 방법 (0) | 2023.02.16 |
| Angular에서 이진 데이터를 읽는 방법ArrayBuffer의 JS? (0) | 2023.02.16 |
| Angular JS를 사용한 모바일 애플리케이션 (0) | 2023.02.16 |