I’m pretty hopeless at PHP, so I figured I’d ask for a bit of help!
I’m using WordPress as a CMS for a music agency site at daviesmusic.com and have lots of extra information for the various artists via custom fields. So far, I’ve just retrieved the custom field values one by one, like so:
<?php
//audio title
$audio_title = get_post_meta($post->ID, 'audio_name', true);
if ($audio_title) :
?>
<p><?php echo $audio_title; ?></p>
This works fine, only I have lots of custom fields that all require different outputs. I have for instance a photo for the artist, an audio file, the title of the audio file and some notes about the audio file, like so:
<?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;
?>
Lots of code. I’m sure there must be a more efficient way to retrieve the values! Any ideas?!
Cheers
Take this example from here:
This will cycle through all specified custom values for the post (id #72 in this example, you can get yours using
$post->ID
as you have in your code). You can use$key
to print the field name, and$value
to print the value of that field. You can get more granular with how they’re displayed using anif elseif else
statement or aswitch
.