I have a custom meta_key called 'sales' this holds information of all sales a sales person has carried out along with a flag to say if it has been authorised, awaiting authorisation or if it has been rejected.
Wordpress is saving each sale as a separate row in the usermeta table, which I don't have an issue with what I am stuck on is updating a specific sales status; i.e changing it from pending (2), to either rejected (0) or approved (1).
I have tried a few ways to do this following advice on other forums etc but it seems like I may be storing the meta data incorrectly in the first place as all the examples are amusing that there is only on row per custom meta_key per user; so the posts are suggesting to update the value, delete all data associated with the key then to upload the modified array.
I currently have the following code but it isn't working as I'd imagined as it is saving the data into another array so becoming further nested.
if(isset($_POST['approved'])) {
$saleStatus = 2;
switch ($_POST['approved']) {
case 'approve':
$saleStatus = 1;
break;
case 'reject':
$saleStatus = 0;
break;
}
$sales = get_user_meta($_POST['repID'], 'sales');
foreach ($sales as $key => $sale) {
if($sale['reg'] === $_POST['carReg']) {
$sales[$key]['approved'] = $saleStatus;
}
}
update_user_meta( $_POST['repID'], 'sales', $sales);
}
UPDATED
$sales = get_user_meta($_POST['repID'], 'sales', true);
foreach ($sales as $key => $value) {
if($value === $_POST['carReg']) {
$sales[0]['approved'] = $saleStatus; //This is overwriting all meta_values making them duplicates
}
}
update_user_meta( $_POST['repID'], 'sales', $sales);
ADDING SALE
if(isset($_POST['customer-name']) && isset($_POST['make']) && isset($_POST['model']) && isset($_POST['reg']) && isset($_POST['condition'])) {
$branch = sanitize_text_field($GLOBALS['user_rep']['repBranch']);
$customer_name = sanitize_text_field($_POST['customer-name']);
$make = sanitize_text_field($_POST['make']);
$model = sanitize_text_field($_POST['model']);
$reg = sanitize_text_field($_POST['reg']);
$condition = sanitize_text_field($_POST['condition']);
$newSales = array(
'branch' => $branch,
'customer_name' => $customer_name,
'make' => $make,
'model' => $model,
'reg' => $reg,
'condition' => $condition,
'time' => time(),
'approved' => 2
);
update_user_meta(wp_get_current_user()->ID, 'sales', $newSales);
}