I am looking for a solution to returning multiple get_post_meta values…
Current I am using a meta box array as follows:
$meta_boxes[] = array(
'id' => 'setlist',
'title' => 'Setlist Information',
'pages' => array('post'),
'fields' => array(
array(
'name' => 'Setlist 1', // field name
'desc' => 'Entry 1', // field description, optional
'id' => $prefix . 'setlist_1', // field id, i.e. the meta key
'type' => 'text', // text box
'std' => '', // default value, optional
'style' => 'width: 100px', // custom style for field, added in v3.1
),
array(
'name' => 'Setlist 2',
'desc' => 'Entry 2',
'id' => $prefix . 'setlist_2',
'type' => 'text',
'std' => '',
'style' => 'width: 100px',
),
and so on so forth (i.e. setlist_3,4,5,6,7,8….)
In my single.php I have:
<?php if ( get_post_meta( $post->ID, 'rw_setlist_1', true ) ) : echo "<li>"; echo get_post_meta( $post->ID, 'rw_setlist_1', true ); echo "</li>"; ?>
<?php endif; ?>
<?php if ( get_post_meta( $post->ID, 'rw_setlist_2', true ) ) : echo "<li>"; echo get_post_meta( $post->ID, 'rw_setlist_2', true ); echo "</li>"; ?>
<?php endif; ?>
<?php if ( get_post_meta( $post->ID, 'rw_setlist_3', true ) ) : echo "<li>"; echo get_post_meta( $post->ID, 'rw_setlist_3', true ); echo "</li>"; ?>
<?php endif; ?>
<?php if ( get_post_meta( $post->ID, 'rw_setlist_4', true ) ) : echo "<li>"; echo get_post_meta( $post->ID, 'rw_setlist_4', true ); echo "</li>"; ?>
<?php endif; ?>
<?php if ( get_post_meta( $post->ID, 'rw_setlist_5', true ) ) : echo "<li>"; echo get_post_meta( $post->ID, 'rw_setlist_5', true ); echo "</li>"; ?>
The set-list values can range from 2 to 30…
Call me crazy, but I feel as if this method causes unnecessary and lengthy load times, am I right? So how would I go about creating a more efficient script for this that would check all the values in the array in a “simpler way”.
The way your code is setup is just wrong, you are making two database calls for each custom field and if you have between 2-30 fields like this then that means you make over 60 calls to the database which can be done with a single call using
get_post_custom()
for ex:
I believe
get_post_meta()
(or more accurately, theget_metadata()
function it calls) retrieves all metadata for a post in one query and then caches it for subsequent calls. As for the verbosity of your code, if they don’t need to be explicitly ordered you could just save them all under a single key and grab them as an array.