0

This question already has an answer here:

I have an issue saving a multi-dimensional array using update_post_meta.

Here's my code ($meta_key and $userID are set up above):

    $read_notices = get_user_meta($userID, $meta_key);

    if (null === $read_notices) {
        $read_notices = array();
    }

    $read_notices[] = $postID;

    update_user_meta($userID, $meta_key, $read_notices);

My problem is that the data is nesting every time so I end up with... Any ideas?

Array
(
    [0] => Array
        (
        [0] => Array
            (
                [0] => Array
                    (
                        [0] => 1823
                    )

                [1] => 1762
            )

        [1] => 1762
    )
)

marked as duplicate by s_ha_dum, kaiser, fuxia Aug 19 '13 at 23:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • get_user_meta(); required a third argument as boolean like get_user_meta($userID, $meta_key, true); – Anjum Aug 19 '13 at 19:42
  • Answered here : wordpress.stackexchange.com/questions/13353/… It's important to add 'true' when getting the meta data so it isn't wrapped in an array. Phew. EG: get_user_meta($userID, $meta_key, true); not get_user_meta($userID, $meta_key); EDIT: You guys were WAY too quick :) Much appreciated. – rob_was_taken Aug 19 '13 at 19:46
0

First af all if (null === $read_notices) is never true, because get_user_meta return false or empty string or empty array. Never return null.

Right way is check if it is empty:

if ( empty ($read_notices) ) { ... }

Then your problem is that using get_user_meta without passing the 3rd parameter as true will return a multidimensional array.

So right code for you scope is:

$read_notices = get_user_meta($userID, $meta_key, true) ? : array();
$prev = $read_notices;
$read_notices[] = $postID;
update_user_meta($userID, $meta_key, $read_notices, $prev);
  • 1
    you can't supply 3rd pram as prev value that's 4th, 3rd is value you want to save in update_user_meta(); – Anjum Aug 19 '13 at 19:46
  • Great response - I did find the answer (comment above) but you were quicker. Thanks G.M. Unfortunately I don't have enough reputation to up-vote you :S – rob_was_taken Aug 19 '13 at 19:50
  • @Anjum +1 from me for your comment. Edited answer adding $prev value. – gmazzap Aug 19 '13 at 20:09
  • @rob_was_taken with edit by Anjum and mine now it should work. – gmazzap Aug 19 '13 at 20:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.