0
votes

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');

foreach ($sales as $key => $sale) {
  $old_sale_data = $sale;
  if($sale['reg'] === $_POST['carReg']) {
    $sale['approved'] = $saleStatus;
     update_user_meta( $_POST['repID'], 'sales', $sale, $old_sale_data);
  }
}
1
Use $sales['approved'] = $saleStatus; instade of $sales[$key]['approved'] = $saleStatus;Domain
Got this working using the updated code as per this answer I've updated the code here as well for clarity on the answer. Thanks for your suggestion.Pierre

1 Answers

0
votes

Here is the full answer. I have updated the question with the correct code. I had to put the update in the loop as my meta data was being stored in separate rows.