0

I am trying to see if I can change an alt text of a featured image on only specific blog posts.

Whenever I upload an image, it allows me to add a default title, caption, alt text and description.

However, I sometimes need to use a different alt text for the same image. The problem is I am only able to use the default alt text I set upon uploading the image whenever I add a featured image.

I have created a custom field via advanced custom fields plugin. Custom field value can be accessed via using the code:

<?php the_field('myvalue'); ?>

Now, I am trying to see if I can come up with some code that allows me to add value from custom field and update the featured image

I am trying to see how i can edit the following code so that the alt attribute can be changed to whatever value in custom field "myvalue"

$title_attribute = the_title_attribute( array( 'echo' => FALSE ) );
the_post_thumbnail(
    'full', 
     array(
        'alt'   => $title_attribute, 
        'title' => $title_attribute 
    )
);
3
  • 'alt' => the_field('myvalue'),?
    – kero
    Commented Sep 5, 2017 at 14:37
  • @kero oh okay, well that worked! Then here is another question... Now i have this $post_thumbnail_attr = array('alt' => get_field('myvalue') );the_post_thumbnail( 'full', $post_thumbnail_attr ); but how can I make the array part conditional? Let's say, if custom field is blank, don't change the alt text. use the default one...
    – ChrisP777
    Commented Sep 5, 2017 at 19:14
  • will this work? if(get_field('alt_image_f')){ $post_thumbnail_attr = array('alt' => get_field('alt_image_f') ); the_post_thumbnail( 'full', $post_thumbnail_attr ); } else the_post_thumbnail();
    – ChrisP777
    Commented Sep 5, 2017 at 19:23

1 Answer 1

0

I think you gave the answer in your last comment.

if (get_field('alt_image_f')){
    $post_thumbnail_attr = array('alt' => get_field('alt_image_f') ); 
    the_post_thumbnail( 'full', $post_thumbnail_attr );
}
else the_post_thumbnail();

Cleaning up your code a bit, the following should work

$custom_image_alt = get_field('alt_image_f');
$post_thumbnail_attr = array();
if ($custom_image_alt) {
    $post_thumbnail_attr['alt'] = $custom_image_alt;
}
the_post_thumbnail('full', $post_thumbnail_attr);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.