Search code examples
phparrayswordpresscustom-fields

PHP Printing a variable from an array of meta keys in WordPress


I'm trying to print the 'artistName' meta keys in a list from the following array:

$postID = $post->ID;
$meta = get_post_meta($postID, $_artistMeta->$postID, TRUE);
print_r($meta);

(which prints the following)

   Array
    (
        [_artistMeta] => Array
            (
                [0] => a:1:{s:10:"artistName";a:2:{i:0;s:33:"la-semilla-de-la-cultura-africana";i:1;s:9:"radiohead";}}
            )
    )

So I want to print/echo the artist names ("la-semilla-de-la-cultura-africana" and "radiohead")... I tried the following two:

foreach ($meta['artistName'] as $artist) {
     echo $artist;
}

which prints nothing... OR

foreach ($meta['_artistMeta'] as $artist) {
     echo $artist['artistName'];
}

which prints "a".

If you can help me with the syntax here, I'd really appreciate it! Thanks!


Solution

  • you should use unserialize to get back a php array

    $postID = $post->ID;
    $meta = get_post_meta($postID, $_artistMeta->$postID, TRUE);
    $artists = unserialize($meta['_artistMeta'][0]);
    foreach ($artists['artistName'] as $artist)
    {
         echo $artist;
    }