samedi 29 novembre 2014

How to add an if statement for one of the custom fields on the following loop?


I have a bunch of custom fields on one of my post types, that is displayed randomly but in a fixed order. The names of the custom fields are always the same, and for every loop there is an increasing counter added to the custom field names.


Like this:



custom_text
custom_text1
custom_text2

custom_image
custom_image1
custom_image2

custom_video
custom_video1
custom_video2


The problem is, there is one field that begins with the number one, like this:



custom_special1
custom_special2
custom_special3


Right now, it's impossible to change this behaviour. Problem is, this makes the custom_special fields show up in the wrong place of the output, the first one shows up together with the fields with the number 1 at then end, instead of with the empty ones.


I need to tweak the code below with some kind of if statement, that says something like:


if $custom_special . $counter {output the result one step down}


Here's my code, I hope some of you gurus out there can help me with a solution!



// max custom field index
$number = 40;
// the counter
$counter = '';
// the meta keys to check for
$keys = array(
'custom_text',
'custom_image',
'custom_video'
);
// all our custom field values
$custom_fields = get_post_custom( get_the_ID() );

// loop over our counter
while( $counter < $number ){
// loop over each of the keys
foreach( $keys as $key ){
// check if a custom field with key + counter exists
if( isset( $custom_fields[ $key . $counter ] ) ){
// output the field
// values will be in an array, 0 is the first index.
// you can loop over these as well if you have multiple values.
echo $custom_fields[ $key . $counter ][0];
}
}
// increment the counter
$counter++;
}


Thanks a lot!


// Jens.





Aucun commentaire:

Enregistrer un commentaire