Home Forums Add-ons Flexible Content Field Alt text using the_subfield not showing


Alt text using the_subfield not showing

  • Hey,

    I have a bit of trouble to get the alt text for my images.

    I have tested the solution in this thread:

    and it works for the regular get_field. But when I try to use the same code for my Flexible Content Field it doesn’t seem to work and I can’t get my head around what’s wrong.

    Have read the documentation without any success.

    The code I have used is as follow:

    *  Loop through a Flexible Content field and display it's content with different views for different layouts
    while(has_sub_field("testalt")): ?>
      <?php if(get_row_layout() == "testaltlayout"): // layout: Content ?>
    <?php $imageID = the_sub_field('imagealt'); ?>
    <?php $image = wp_get_attachment_image_src( $imageID, 'full' ); ?>
    <?php $alt_text = get_post_meta($imageID , '_wp_attachment_image_alt', true); ?>
    <img src="<?php echo $image[0]; ?>" alt="<?php echo $alt_text; ?>" />
      <?php endif; ?>
    <?php endwhile; ?>
  • Hi!

    Make sure that your image field is set to return the image ID and not the URL or object!

  • Hi Jonathan and thanks for your quick reply.

    I have set the image field to ID. But after your reply I checked the code again and found the error.

    I had used the_sub_field instead of get_sub_field.

    So thanks for validating that your solution also worked on sub fields that pointed me in the right direction.

    I saw your answer in this topic ( and used the last solution you provided.

    Final code that worked for me.

    Code added to function.php

    // Alt text for ACF get_sub_field images
    function get_image_with_alt($imagefield, $postID, $imagesize = 'full'){
    $imageID = get_sub_field($imagefield, $postID); 
    $image = wp_get_attachment_image_src( $imageID, $imagesize ); 
    $alt_text = get_post_meta($imageID , '_wp_attachment_image_alt', true); 
    return '<img src="' . $image[0] . '" alt="' . $alt_text . '" />';

    And then all it like this where you want the image in your template:

    <?php echo get_image_with_alt('NAME OF THE IMAGE FIELD', get_the_ID(), ''); ?>
Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Alt text using the_subfield not showing’ is closed to new replies.

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.