问题
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!
回答1:
You're using the correct method to set the user's first name.
set_first_name()
won't permanently save a value on its own. When you've set all the properties you wish to update you need to call the save()
method.
if ( isset( $_POST['first_name'] ) ) {
$wc_current_user->set_first_name( $_POST['first_name'] );
$wc_current_user->save();
}
- https://woocommerce.wordpress.com/2016/10/27/the-new-crud-classes-in-woocommerce-2-7/
- https://github.com/woocommerce/woocommerce/wiki/CRUD-Objects-in-3.0
回答2:
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();
}
来源:https://stackoverflow.com/questions/43904515/setting-customer-user-data-with-crud-object-in-woocommerce