Search code examples
phpwordpresswoocommercefile-put-contents

Is file_put_contents a reliable way to check value of some variables?


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?


Solution

  • 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).