How do I update a specific object in an array, in user meta?

I have this array, below, to set custom user meta (lh_userbadges) in user_meta but I’m not exactly sure how to update just parts of the array later on…

$lh_user_badges = array(
    'lh_userbadge_comments25' => '0',
    'lh_userbadge_comments50' => '0',
    'lh_userbadge_comments75' => '0',
    'lh_userbadge_comments100' => '0',
    'lh_userbadge_comments150' => '0',
    'lh_userbadge_submited' => '0',
    //etc.
);
update_user_meta($user_id, 'lh_userbadges', $lh_user_badges);

From what I gathered in other stack overflow questions (How to update serialized data in the user meta data is a good example BUT it just increments, which I don’t want. I want to set a specific number just once.), I think it something along these lines but, I’m just not sure….

Read More
$meta_value = get_user_meta($user_id, 'lh_userbadges', false);
$meta_value['lh_userbadge_comments25']  //....?

So, for example, I just want to update the object lh_userbadge_comments25 from lh_userbadges from 0 to (lets say) 25, how would I do that? I think I’m on the right track with that 2nd part of code but I do not know…

Any ideas? Also, I’m not sure if this is the best way to do it but I figured this would save database clutter if I did it in this format rather than each type being it’s own meta item.

Related posts

Leave a Reply

1 comment

  1. You can just assign a new value to the 1h_userbadge_comments25 key.

    Like so…

    <?php
    $meta_value = get_user_meta($user_id, 'lh_userbadges', false);
    // just assign this key a new value
    $meta_value['lh_userbadge_comments25'] = 25;
    

    Then just save it again.

    <?php
    update_user_meta( $user_id, 'lh_userbadges', $meta_value );
    

    Whether or not storing all of those values as an array is the correct way to do this is really up to you. Do you need to do a lot of changing around like this? Do the all these values make sense together? Without knowing more about what you’re doing, that’s a hard question to answer.