Advanced Custom Fields Wordpress Plugin: Function for displaying images

Here is a handy little function I put together for outputting images in Wordpress when using the image (type: object) on the Advanced Custom Fields plugin. I have modified it slightly to include images in sub fields from repeaters and haven't tested it yet but it should still work:

function get_image($ACF_fieldname, $attributes=null, $sub=false)
    {
	    if($sub)
	    	{
		    	$image =  get_sub_field($ACF_fieldname);
	    	}
	    else
	    	{
		    	$image =  get_field($ACF_fieldname);
	    	}
        
        if(!empty($image))
            {
                if(isset($image['alt']))
                	{
				$alt = ' alt="'.$image['alt'].'" ';
                	}
                else
                	{
	                	$alt = ' alt="" ';
	                }
                if(isset($image['title']))
                	{
						$title = ' title="'.$image['title'].'" ';
                	}
                return '<img src="'.$image['url'].'" '.$alt.$title.$attributes .' />';
            }
    }

Then in your templates you can either get the image, or echo it out like so:

// an image
echo get_image('My_Image', 'class="imgClass" rel="lightbox"');

// a sub image
echo get_image('My_Image', 'class="imgClass" rel="lightbox"', true);

Hopefully you find this useful and if you do use it and find it useful, feel free to leave a comment or even better...link back to this article ;)

Leave a Comment

All comments are appreciated. Comments are moderated before appearing on the site, so please don't bother trying leaving spam! Only genuine comments will be shown.

Your Name

Email Address (optional)

What year is it? (Spam Prevention)

Comment

moo.com business card printing123-reg Domain names

What's All This About?

Deanblog is a collection of articles written by Dean Morgan from Deanzod Limited. The aim of the site is to provide helpful information for everyone from web designers & developers right through to website owners. I will try and keep a good balance of information such as php/mySQL tutorials, html/css tutorials along with marketing ideas and advice for website owners.

Recent Articles