2010-12-22 100 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