1

I'm trying to set up a page with an image gallery where, if the alt field is empty, it'll display whatever is in the caption (at least one or the other will always have content). This is my current code, which is displaying nothing at all.

$image_all = wp_prepare_attachment_for_js($item->ID);

if (empty($image_all['alt'])) { 
    echo $image_all['caption']; 
} else { 
    echo $image_all['alt']; 
}

If I just put in echo $image_all['alt']; (or 'caption') it displays just fine. But using the if statement results in nothing displaying at all.

What am I doing wrong?

treyBake
  • 6,440
  • 6
  • 26
  • 57
Laura Sage
  • 201
  • 1
  • 11
  • 1
    [you should enable PHP errors](https://stackoverflow.com/questions/845021/how-can-i-get-useful-error-messages-in-php) – treyBake Feb 04 '20 at 15:00
  • 1
    var_dump $image_all – B001ᛦ Feb 04 '20 at 15:01
  • which PHP version are you on? Try `echo $image_all['alt'] ?? $image_all['caption'];` (if alt is set and not null or empty it will echo, if it is null or empty it does caption instead) – delboy1978uk Feb 04 '20 at 15:02
  • What does `var_dump(empty($image_all['alt']));die;` returns? – Rahul Singh Feb 04 '20 at 15:07
  • try `isset` instead of `empty` – David Shindler Feb 04 '20 at 15:12
  • @DavidShindler `empty()` covers `isset()` – treyBake Feb 04 '20 at 15:18
  • var_dump shows nothing. Very strange. And I was wrong in my initial post - 'caption' also shows nothing, on an image that I know has a caption. – Laura Sage Feb 04 '20 at 15:25
  • @delboy1978uk `??` ignores *empty* values unless they are null. `0`, `false`, etc will still be considered "valid". – Jeto Feb 04 '20 at 15:25
  • @LauraSage var_dump is a good practice in development environment. You should also enable error_reporting(1) so you may see all warnings, notices and errors at once. Also consider looking into following reference. https://developer.wordpress.org/reference/functions/wp_prepare_attachment_for_js/# – Sam Feb 04 '20 at 15:28
  • I have error messages turned on, so I do see the notices/errors. I think the trouble may be where caption comes from. It seems that perhaps I need to be using something like wp_get_the_post_thumbnail_caption($item) instead. But even that's not working. – Laura Sage Feb 04 '20 at 15:36

1 Answers1

0

Well I feel pretty stupid right now. I was modifying code for the display page, but was trying to view the results from the search page. I really need to set this up with an include file so I only need to make changes in one place. I'm really sorry for wasting everyone's time. My original code works just fine.

Laura Sage
  • 201
  • 1
  • 11