skip to Main Content

I have a wordpress project that is using ACF fields to pass images/video into a carousel. How would I get the alt text for the associated image?

I have tried to get_field(‘image’) and various get_sub_field() calls, but image does not seem to be a field even though get_sub_field(‘still_image_url’) and get_sub_field(‘image_link’) are already pulling in the respective data for those fields.

I’m not even sure how to get the id for the image. Another php file is using the_ID();, but that is not working here.

          <?php while (have_rows('top_slider')) : the_row(); ?>
            <?php
                $video_url = get_sub_field('video_url');
                $video_url_responsive = get_sub_field('video_url_responsive');
                $video_link = get_sub_field('video_link');
                $image_url = get_sub_field('still_image_url');
                $image_link = get_sub_field('image_link');
                $has_target = strpos($image_link, '/') !== 0;
            ?>

2

Answers


  1. Make sure you are using the return format of the Image either as IMAGE ARRAY or IMAGE ID.

    Use the below code to get the ALT tag of the image if the return format is IMAGE ARRAY.

     <?php 
    $image =get_sub_field('image');
    if( !empty($image )): ?>
    <img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>" />
    <?php endif; ?>
    

    Use the below code to get the ALT tag of the image if the return format is IMAGE ID.

    $image_id = get_sub_field('image');
    $img_url = wp_get_attachment_image_src($image_id, 'full');
    $image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
    $image_title = get_the_title($image_id);
    ?>
    <img src="<?php echo $img_url[0]; ?>" width="<?php echo $img_url[1]; ?>" height="<?php echo $img_url[2]; ?>" alt="<?php echo $image_alt; ?>" title="<?php echo $image_title; ?>"> 
    

    Here the "image" denotes the field name which you set while creating the field.

    get_sub_field('image');
    

    enter image description here

    Refer the image for understanding about Field Name, Return Format etc

    Login or Signup to reply.
  2. You can see the image id and other details on the REST API if you will set the options to show on REST API.

    After adding the contents to WP REST API, you can display the pages’ content on the WP REST API as you can use this example link:

    https://write-your-site-url-here/wp-json/wp/v2/pages

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search