Is it possible to create a function that works within a theme template when calling an ACF image or gallery?
Something like… show alt text if there is any, if not show image title text instead, if neither show custom text site title or something…
I’ve tried the following but with no luck, i think it fails when called within a foreach gallery and unsure how to make it work…
function image_alt_tag($alt) {
global $post;
$image = get_field( $alt, $post->ID );
if ( $image['title'] ) {
echo $image['title'];
}
elseif ( $image['alt'] ) {
echo $image['alt'];
}
else {
echo('no image title or alt tag do this');
}
return $alt;
}
And then calling this within the theme acf…
<img alt="<?php image_alt_tag('field_name'); ?>">
Ideally i would like to develop this for all images used across a site, but this is just the starting point.
functions.php
function image_alt_tag( $image = null )
{
if( $image == null ) return;
echo $image['alt'] ? $image['alt'] : $image['title'] ? $image['title'] : 'No ALT-Tag';
}
within the wp loop
<?php $images = get_field( 'gallery' ); ?>
<?php if( $images ): ?>
<?php foreach( $images as $image ): ?>
<img src="<?=$image['url']?>" alt="<?php image_alt_tag( $image ); ?>" />
<?php endforeach; ?>
<?php else: ?>
<p>No images</p>
<?php endif;?>
I do not know what your theme or template looks like. I have not explained anything, but you are welcome to ask if something is not understandable.
Hi, thank you for that.
Will that for a single image as well as within a foreach galley?
If possible can you explain this bit…
if( $image == null ) return;
echo $image['alt'] ? $image['alt'] : $image['title'] ? $image['title'] : 'No ALT-Tag';
Why no IF tags, is it just reading through and will spit something out when it finds it there?
// if no image, return null
if( $image == null )
return;
// shorthand for if
echo $image['alt'] ? $image['alt'] : $image['title'] ? $image['title'] : 'No ALT-Tag';
// equal
if( $image['alt'] ) {
echo $image['alt'];
} elseif( $image['title'] ) {
echo $image['title'];
} else {
echo 'No ALT-Tag';
}
My answer refers to the output of a gallery field from ACF. If you want to use the function for a single image (from ACF), you need to do the following:
<?php $image = get_field( 'image' ); ?>
<img src="" alt="<?php image_alt_tag( $image ); ?>" />
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.