2010-12-22 151 views
1

我在PHP很无望,所以我想我会寻求一些帮助!多个wordpress自定义帖子元值

我使用WordPress作为CMS的音乐代理网站daviesmusic.com,并通过自定义字段为各种艺术家提供大量额外信息。到目前为止,我刚刚取回的自定义字段值一个接一个,像这样:

<?php 
    //audio title 
    $audio_title = get_post_meta($post->ID, 'audio_name', true); 
    if ($audio_title) : 
?> 

    <p><?php echo $audio_title; ?></p> 

这工作得很好,只有我有很多这都需要不同的输出自定义字段。我有一个实例艺术家照片,音频文件,音频文件的标题和有关音频文件的一些注意事项,比如:

<?php 
    //profile image 
    $profile_pic = get_post_meta($post->ID, 'profileimage', true); 
    if($profile_pic) : 
?> 

    <img class="post-thumb-single" src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $profile_pic; ?>&a=t&h=278&w=278&zc=1" alt="<?php the_title(); ?>" /> 

<?php 
    endif; 
    //photographer 
    $photographer = get_post_meta($post->ID, 'photographer', true); 
    if($photographer) : 
?> 

    <p id="photographer">Photographer: <b><?php echo $photographer; ?></b></p> 

<?php 
    endif; 
    //audio title 
    $audio_title = get_post_meta($post->ID, 'audio_title', true); 
    if ($audio_title) : 
?> 

    <h4 class="nsmb">Audio files</h4> 

    <p><?php echo $audio_title; ?></p> 

<?php 
    //audio file 
    $audio = get_post_meta($post->ID, 'audiofile', true); 
    if ($audio) : 
?> 


<p class="audio" id="audioplayer_1">Sorry, there was a problem loading the file.</p> 
<script>AudioPlayer.embed("audioplayer_1", {soundFile: "<?php echo $audio; ?>"});</script> 


    <?php 
    $audio_credits_1 = get_post_meta($post->ID, 'audio_credits_1', true); 
    if ($audio_credits_1) : 
    ?> 

    <p class="audio_cred"><?php echo $audio_credits_1; ?></p> 

    <?php 
     endif; endif; endif; 
    ?> 

大量的代码。我确定必须有更高效的方式来检索值!有任何想法吗?!

干杯

+0

将它包装成一个函数,该函数接受一组键并根据键输出适当的HTML?想要一个例子吗? – t31os 2010-12-22 13:59:44

回答

3

采取从here这个例子:

$custom_fields = get_post_custom(72); 
$my_custom_field = $custom_fields['my_custom_field']; 
foreach ($my_custom_field as $key => $value){ 
    echo $key . " => " . $value . "<br />"; 
} 

通过所有指定的自定义值,会有周期后(ID#72在这个例子中,你可以得到你使用$post->ID你有在你的代码中)。您可以使用$key来打印字段名称,并使用$value来打印该字段的值。您可以使用if elseif else声明或switch更详细地了解它们的显示方式。

+0

对不起,我花了6个月的时间回复!感谢您的回答! – 2011-07-01 11:04:28