如何使用GET_POST_CUSTOM_VALUES返回数组的值

时间:2011-12-20 作者:sea_monster

我有一个自定义的帖子类型,叫做albums 其中的自定义字段称为tracklist 这是一个包含song_titleduration. 我想打印每张专辑上的歌曲列表。

这样考虑数组层次结构对我很有帮助:

albumlist
  album
    tracklist
      track
        song_title
        duration
到目前为止,我知道了如何深入到tracklist数组,但不知道如何显示其中歌曲标题的值。

$albums = get_posts(array(
  \'post_type\' => \'album\',
  \'meta_key\'  => \'tracklist\'
));

if($albums) {
  foreach($albums as $album) {
    echo get_the_title($album->ID) . "<br>"; // Displays album\'s title
    $tracklist = get_post_custom_values(\'tracklist\', $album->ID);

    foreach($tracklist as $track) {
      echo $track . "<br>"; // Displays "12" (there are 12 tracks on this album)
    }
  }
}
不管怎样,我已经花了几个小时来解决这个问题,但已经很晚了!一旦我到达tracklist array,我如何钻入曲目并获得歌曲标题?

谢谢你能提供的任何帮助。

2 个回复
最合适的回答,由SO网友:booota 整理而成

如果你改变

foreach($tracklist as $track) {
  echo $track . "<br>"; // Displays "12" (there are 12 tracks on this album)
}

foreach($tracklist as $key => $value ) {
    echo "$key  => $value (\'tracklist\')<br />"; // Displays "12" (there are 12 tracks on this album)
}
那你得到了什么?

SO网友:Rutwick Gangurde

Try this...

$albums = get_posts(array(
        \'post_type\' => \'album\',
        \'meta_key\'  => \'tracklist\'
));

if(isset($albums) && !empty($albums))
{
    foreach($albums as $album)
    {
        echo get_the_title($album->ID) . "<br>"; // Displays album\'s title
        $tracklist = get_post_meta($album->ID, \'tracklist\', true);

        if(isset($tracklist) && !empty($tracklist))
        {
            foreach($tracklist as $track)
            {
                 echo $track . "<br>"; // Displays "12" (there are 12 tracks on this album)
            }
        }
        else
        {
            echo "No Tracklist Added";
        }
    }
}
结束

相关推荐