Search code examples
phpwordpresswoocommerceaccountuser-data

Setting customer user data with CRUD object in Woocommerce


I'm trying to set a new value for the first_name for a user on woocommerce, i want to do this using the 'CRUD Objects in 3.0' present in the last documentation of woocommerce 3.0.

Só i'm definig the variable:

$wc_current_user = WC()->customer;

This return an instance of the class WC_Customer with has an array of $data with data about customer like $first_name, $last_name, $email, $billing_address array and so on...

i'm trying to rewrite the edit-account.php form and want to submit this data on this object, he provide the getters and setters to do this, but seems the setter ins't working, he is not saiving the data.

I'm doing this:

I have a form with takes the first name from the user, this is working fine, i'm using the ->get_first_name and is working fine.

  <form class="woocommerce-account-information" action="" method="post">

    <label>First Name</label>
     <input type="text" name="first_name" value="<?php echo 
     $wc_current_user->get_first_name()?>"/>

     <button type="submit">SAVE</button>
  </form>

The Problema is here, when i try to submit this data using a setter, which in this case is 'object -> set_first_name' and 'object->save()', nothing happens, someone can help me?

Here is my code:

  if( isset($_POST['first_name'] ) ){
     $wc_current_user->set_first_name($_POST['first_name']);
     $wc_current_user->save();

   }

//THIS ^ DON'T WORK, do you know what is wrong?

I'm interested in knowing both the old and the new method, if anyone can help me, it will be a great help. Thank you!


Solution

  • I find a solution for this problem, when you use object like this you need to use the $object-save() method that Nathan has said plusthe $object->apply_changes(); to submit replace the data on data-base:

    public function apply_changes() {
        $this->data    = array_replace_recursive( $this->data, $this->changes );
        $this->changes = array();
    }
    

    My working code looks like this:

           $wc_current_user = WC()->customer;
    
           if ( isset($_POST['first_name']) ) {
                $wc_current_user->set_first_name($_POST['first_name']);
                $wc_current_user->save();
                $wc_current_user->apply_changes();
          }