• Resolved elliottprice

    (@elliottprice)


    When I add an array as custom User Meta, the format seems to be thrown off.

    This is the code I’m using to create the data:

    $array = array( 'customkey1' => 1, 'customkey2' => 0 );
    
    add_user_meta( $user_ID, 'custom', $array);

    And this is what comes out in the User Meta:

    [custom] => Array ( [0] => a:2:{s:10:"customkey1";i:1;s:10:"customkey2";i:0;} ) )

    How do I then access the data inside the array or update it? I’m not familiar with this format for an array… I’m used to using: $user_meta[‘custom’][0][‘customkey1’] but that doesn’t work, it returns ‘a’. Is this even the right way to create an array in the user meta?

    Thanks in advance

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Hi elliottprice

    How do you retrieve the user meta? With get_user_meta()?
    http://codex.wordpress.org/Function_Reference/get_user_meta

    Thread Starter elliottprice

    (@elliottprice)

    Hi keesiemeijer, thanks for replying. Yes, I’m using the get_user_meta() function, and passing that to a variable. Both the function and the variable return the same result, I’m not sure what kind of syntax is being used there.

    I’m also looking into storing the data in the WP Options table.

    Moderator keesiemeijer

    (@keesiemeijer)

    Strange.

    When I do this.

    <?php
    $array = array( 'customkey1' => 1, 'customkey2' => 0 );
    
    // add the user meta
    add_user_meta( 1, 'custom', $array);
    
    // retrieve the user meta
    $data = get_user_meta(1, 'custom', false);
    
    // print the user meta
    echo '<pre>';
    print_r($data);
    echo '</pre>';
    ?>

    It prints a normal array:

    Array
    (
        [0] => Array
            (
                [customkey1] => 1
                [customkey2] => 0
            )
    
    )

    The data you describe is an serialized array used for storing data in the database.

    Try the maybe_unserialize() function to unserialize the data.

    $data = get_user_meta( 1, 'custom', false );
    $data = maybe_unserialize( $data );

    http://codex.wordpress.org/Function_Reference/maybe_unserialize

    Thread Starter elliottprice

    (@elliottprice)

    I realized what I was doing wrong – I was getting the entire get_user_meta() and passing all of it to a variable, then trying to access the custom key from there – instead of specifying the key like you did with get_user_meta( $user_id, ‘key’ ). that works much better.

    Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Arrays in custom User Meta data?’ is closed to new replies.