0

My website is built with wordpress+woocommerce.

For learning purpose, I am trying to check an order's detail once it is completed using file_put_contents. Here is the code:

add_action( 'woocommerce_order_status_completed', 'change_role_on_first_purchase' );

function change_role_on_first_purchase( $order_id ) {
  $order = new WC_Order( $order_id );
  // $user = new WP_user($order->user_id);
  file_put_contents('order.json',json_encode($order));
  file_put_contents('userid.json',json_encode($order->user_id));
  }
}

While the second file_put_contents does write the correct user ID into userid.json, order.json's content is just {}. Obviously $order is not empty, then why file_put_contents is outputting an empty json object?

shenkwen
  • 3,536
  • 5
  • 45
  • 85
  • Maybe https://stackoverflow.com/questions/4697656/using-json-encode-on-objects-in-php-regardless-of-scope is relevant... for title of question though i would use `file_get_contents` ... or use a database – user3783243 Jan 28 '22 at 18:22
  • 2
    I'm trying to understand why you would choose to use file_put_contents? – Howard E Jan 28 '22 at 19:57
  • @HowardE I am aware WP has its own debug method if that is what you mean. But for now `file_put_contents` is easier for me. – shenkwen Jan 29 '22 at 17:09
  • @HowardE And I will be very glad to learn in what kind of cases file_put_contents is incompetent. – shenkwen Jan 29 '22 at 17:11
  • I never said it was incompetent. I just asked you why. Debugging. I see. – Howard E Jan 29 '22 at 17:55

1 Answers1

3

Short Answer

Before you can json_encode($order), you need to get the order's data as a plain unprotected array:

$order = new WC_Order( $order_id );
$order_data = $order->get_data(); // ADD THIS
file_put_contents('order.json',json_encode($order_data));

Long Answer Read: json_encode empty with no error TLDR: Basically, json_encode works best when an object has public properties. WC_Order doesn't have any, so it results in an empty object and that's why they created the get_data() method (to expose the data as a plain "unprotected" associative array) (perfect food for json_encode).

Fritz Bester
  • 162
  • 1
  • 6