以JSON格式从Woocommerce导出订单

时间:2014-01-14 14:52:56

标签: wordpress woocommerce json orders

我正在尝试从wordpress Woocommerce的插件中导出订单项,然后在wordpress中创建一个模板,用我的查询获取数组中的订单数据

<?php 
//query
      global $woocommerce; 
        global $wpdb; 
        global $product;
      $args = array(
        'post_type'     => 'shop_order',
            'orderby' => 'ID',
        'post_status'     => 'publish',
            'posts_per_page' => -1,
        'tax_query' => array(array(
                            'taxonomy' => 'shop_order_status',
                            'field' => 'slug',
                            'terms' => array('processing'))));
      $loop = new WP_Query( $args );
      $order_id = $loop->post->ID;
      $order = new WC_Order($order_id); 
        $product = new WC_Product($order_id);

  //Email verificacion if is suscribed or not
  $sql = "SELECT * FROM dsr_wysija_user WHERE email='". $order->order_custom_fields['_billing_email'][0] ."'" ;
  $res = mysql_query($sql);
  if (mysql_num_rows($res)== 1){
  $email = 'true';
  }else{
    $email = 'false';
}
// Getting names of categories and quantity 
foreach($order->get_items() as $item) 
{
   $item['name']; 
   $item['qty'];
}


//Collecting data in ARRAY
  $json[]= array(
        "salutation"=>''. $order->order_custom_fields['_billing_titel'][0] .'' ,
        "title"=>''. $order->order_custom_fields['_billing_anrede'][0] .'',
        "first_name"=>''. $order->order_custom_fields['_billing_first_name'][0] .'',
        "last_name"=>''. $order->order_custom_fields['_billing_last_name'][0] .'',
        "street"=>''. $order->order_custom_fields['_billing_address_1'][0] .'',
        "street_number"=>''.$order->order_custom_fields['_billing_address_2'][0] .'',
        "address_supplement"=>''. $order->order_custom_fields['_billing_company'][0] .'',
        "zipcode"=>''. $order->order_custom_fields['_billing_postcode'][0] .'',
        "city"=>''. $order->order_custom_fields['_billing_city'][0] .'',
        "country"=>''. $order->order_custom_fields['_billing_country'][0] .'',
        "terms_accepted"=>'true',
        "receiving_mails_accepted"=>''.$email.'',   
        "email"=>''. $order->order_custom_fields['_billing_email'][0] .'',
        "original_created_at"=>''.$order->order_date.'', );


  //Starting While
  while ( $loop->have_posts() ) : $loop->the_post();
  //Printing Output array
  // echo (json_format($json))
?>


<?php endwhile; ?>

输出就像那样

{
  "salutation": "Arq.",
  "title": "herr",
  "first_name": "Ted",
  "last_name": "Mosby",
  "street": "Manhattan",
  "street_number": "20",
  "address_supplement": "How I met your mother",
  "zipcode": "MANHATTAN",
  "city": "New York",
  "country": "ES",
  "terms_accepted": "true",
  "receiving_mails_accepted": "true",
  "email": "ted@mosby.com",
  "original_created_at": "2014-01-07 03:34:31"
}     

但我需要的是

{
  "salutation": "Arq.",
  "title": "herr",
  "first_name": "Ted",
  "last_name": "Mosby",
  "street": "Manhattan",
  "street_number": "20",
  "address_supplement": "How I met your mother",
  "zipcode": "MANHATTAN",
  "city": "New York",
  "country": "ES",
  "terms_accepted": "true",
  "receiving_mails_accepted": "true",
  "email": "ted@mosby.com",
  "original_created_at": "2014-01-07 03:34:31"
  "items": [
    {
      "campaign_number": 301,
      "item_number": 1
    },
    {
      "campaign_number": 301,
      "item_number": 2
    },
    ...
  ]
},
...
]
}   

2 个答案:

答案 0 :(得分:2)

这是我用来获得与WooCommerce Orders REST API相同的精确结构的方法:

function declareHelperClass()
{
  /**
   * wp-content/plugins/woocommerce/packages/woocommerce-rest-api/src/Controllers/Version3/class-wc-rest-orders-controller.php
   */
  class WC_REST_Orders_Controller_Wrapper extends WC_REST_Orders_Controller
  {

    public function get_formatted_item_data($data)
    {
      return parent::get_formatted_item_data($data);
    }
  }
}

declareHelperClass();

$order = wc_get_order($orderId);
if (!$order) {
  error_log("Error: Cannot find order $orderId");
  return false;
}

$ordersController = new WC_REST_Orders_Controller_Wrapper();
$orderData = $ordersController->get_formatted_item_data($order);

echo json_encode($orderData, JSON_PRETTY_PRINT);

示例输出:

{
  "id": 727,
  "parent_id": 0,
  "number": "727",
  "order_key": "wc_order_58d2d042d1d",
  "created_via": "rest-api",
  "version": "3.0.0",
  "status": "processing",
  "currency": "USD",
  "date_created": "2017-03-22T16:28:02",
  "date_created_gmt": "2017-03-22T19:28:02",
  "date_modified": "2017-03-22T16:28:08",
  "date_modified_gmt": "2017-03-22T19:28:08",
  "discount_total": "0.00",
  "discount_tax": "0.00",
  "shipping_total": "10.00",
  "shipping_tax": "0.00",
  "cart_tax": "1.35",
  "total": "29.35",
  "total_tax": "1.35",
  "prices_include_tax": false,
  "customer_id": 0,
  "customer_ip_address": "",
  "customer_user_agent": "",
  "customer_note": "",
  "billing": {
    "first_name": "John",
    "last_name": "Doe",
    "company": "",
    "address_1": "969 Market",
    "address_2": "",
    "city": "San Francisco",
    "state": "CA",
    "postcode": "94103",
    "country": "US",
    "email": "john.doe@example.com",
    "phone": "(555) 555-5555"
  },
  "shipping": {
    "first_name": "John",
    "last_name": "Doe",
    "company": "",
    "address_1": "969 Market",
    "address_2": "",
    "city": "San Francisco",
    "state": "CA",
    "postcode": "94103",
    "country": "US"
  },
  "payment_method": "bacs",
  "payment_method_title": "Direct Bank Transfer",
  "transaction_id": "",
  "date_paid": "2017-03-22T16:28:08",
  "date_paid_gmt": "2017-03-22T19:28:08",
  "date_completed": null,
  "date_completed_gmt": null,
  "cart_hash": "",
  "meta_data": [
    {
      "id": 13106,
      "key": "_download_permissions_granted",
      "value": "yes"
    }
  ],
  "line_items": [
    {
      "id": 315,
      "name": "Woo Single #1",
      "product_id": 93,
      "variation_id": 0,
      "quantity": 2,
      "tax_class": "",
      "subtotal": "6.00",
      "subtotal_tax": "0.45",
      "total": "6.00",
      "total_tax": "0.45",
      "taxes": [
        {
          "id": 75,
          "total": "0.45",
          "subtotal": "0.45"
        }
      ],
      "meta_data": [],
      "sku": "",
      "price": 3
    },
    {
      "id": 316,
      "name": "Ship Your Idea &ndash; Color: Black, Size: M Test",
      "product_id": 22,
      "variation_id": 23,
      "quantity": 1,
      "tax_class": "",
      "subtotal": "12.00",
      "subtotal_tax": "0.90",
      "total": "12.00",
      "total_tax": "0.90",
      "taxes": [
        {
          "id": 75,
          "total": "0.9",
          "subtotal": "0.9"
        }
      ],
      "meta_data": [
        {
          "id": 2095,
          "key": "pa_color",
          "value": "black"
        },
        {
          "id": 2096,
          "key": "size",
          "value": "M Test"
        }
      ],
      "sku": "Bar3",
      "price": 12
    }
  ],
  "tax_lines": [
    {
      "id": 318,
      "rate_code": "US-CA-STATE TAX",
      "rate_id": 75,
      "label": "State Tax",
      "compound": false,
      "tax_total": "1.35",
      "shipping_tax_total": "0.00",
      "meta_data": []
    }
  ],
  "shipping_lines": [
    {
      "id": 317,
      "method_title": "Flat Rate",
      "method_id": "flat_rate",
      "total": "10.00",
      "total_tax": "0.00",
      "taxes": [],
      "meta_data": []
    }
  ],
  "fee_lines": [],
  "coupon_lines": [],
  "refunds": [],
  "_links": {
    "self": [
      {
        "href": "https://example.com/wp-json/wc/v3/orders/727"
      }
    ],
    "collection": [
      {
        "href": "https://example.com/wp-json/wc/v3/orders"
      }
    ]
  }
}

答案 1 :(得分:1)

假设这是你的物品循环

// Getting names of categories and quantity 
foreach($order->get_items() as $item) 
{
   $json['items'][] = array (
       'name' => $item['name'],
       'quantity' => $item['qty']
}

while ( $loop->have_posts() )

之前尝试上面的代码