Hi.
Im trying to display my custom types fields in a loop with foreach.. i have searched over and over and the only thing i found out was to add (array) to my code, but it still doesnt work like it should..
Im trying to put the image url inside the img tag for each image, but now it only renders 1 image and puts all paths in that src..
my code:
$thumbnails = types_render_field("inspirations-billeder", array("size"=>"large","url"=>"true"));
foreach((array)$thumbnails as $thumbnail ) {
echo "<li><a href='{$thumbnail}' title='' target='_blank' class='zoom' data-rel='prettyPhoto[product-gallery1]'><img src='{$thumbnail}' width='' height='' alt='' /></a></li>";
};
If i remove (array) from the code i get a PHP error "Warning: Invalid argument supplied for foreach() in"
Alternately, i figured i could make this in a View by just looping the custom fields, but that didnt work either because you cant filter a view by current post id.. so that makes all the images stored in that field render.. so that wont work either.
Either solution / fixes are welcome at the time, as i unfortunately had to do this on a production site.
Thank you very much.
Dear Thomas,
Looking at your PHP code example. types_render_field outputs a string consisting of several images. You need to use a separator to separate them inside a string (e.g. a comma) then explode them into an array using comma as separator. You are not using a separator, so when you cast into an array, only the first image is rendered.
Below is a working example (I tested this) by extending your original PHP code provided. I added some fixes to it, this should work now 🙂
/** Display repeating image fields using types_render_field
/* Start
*/
$thumbnails = types_render_field("inspirations-billeder", array("size"=>"large","url"=>"true","separator"=>","));
if ( ( is_string( $thumbnails ) ) && (!( empty( $thumbnails ) ) ) ) {
//Has images to display
//Put all images in an array
$thumbnails = explode(",", $thumbnails);
if ( ( is_array( $thumbnails ) ) && (!( empty( $thumbnails ) ) ) ) {
foreach( $thumbnails as $thumbnail ) {
echo "<li><a href='{$thumbnail}' title='' target='_blank' class='zoom' data-rel='prettyPhoto[product-gallery1]'><img src='{$thumbnail}' width='' height='' alt='' /></a></li>";
};
}
}
/**End*/
Cheers,
Emerson
Hi Emerson, thank you very much for assisting me.
What you say, makes perfect sense, i never thought about that of the comma separator, didnt know that.
Thank you for giving me the understanding of what went wrong, instead of just a solution - this is what i will call perfect support.
"give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime" - just just taught me how to fish 🙂
PS: Your code worked perfect 🙂
Have a pleasant day.
Regards