Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if/else get_field() with WordPress

I'm trying to give a client some options in the WP backend to customize a carousel that is displayed on their website's homepage. I am using Advanced Custom Fields to handle getting the input from the client. I want to give them two options:

Option #1) Allows the client to insert a string of text to be displayed ('carousel_title_text')

Option #2) Allows the client to upload a logo to be displayed ('carousel_logo')

I want the code to check for title text, and if there is none, display the logo instead. I haven't yet decided what will happen if both fields are empty. Anyway, here is what I've come up with:

<?
if( get_field('carousel_title_text') ) { ?>
  <h2 class="promo"><?php the_field('carousel_title_text');?></h2>
<? } elseif( get_field('carousel_logo') ) {
  the_field('carousel_logo');
}
?>

The 'carousel_title_text' displays as long as there is an input, but when it's empty and 'carousel_logo' is not, it does not properly output the logo. Can anyone tell me what I'm doing wrong or if there's a better approach?

Thanks in advance,

like image 729
marcusnjones Avatar asked Jun 01 '15 16:06

marcusnjones


1 Answers

If I get it right, your problem is not with the If/Else statement but with the logo field. I assume you properly configured this field (carousel_logo) as Image in ACF.

Image fields offer three different Return Value possibilities:

Return Values for Image fields

Note: In some versions of ACF you'll found Image Object instead of Image Array, but it's conceptually the same.

None of them will show your image properly if you just use the_field('carousel_logo'); in your template. So, how do you get your logo?

If you want the easiest solution, choose Image URL as Return Value for your logo field and print it like that:

<?
$title = get_field('carousel_title_text');
$logo = get_field('carousel_logo');

if (!empty($title)) : ?>
    <h2 class="promo"><?= $title ?></h2>
<?php elseif (!empty($logo)) : ?>
    <img class="logo" src="<?= $logo ?>">
<?php else: ?>
    <!-- No title, no logo -->
<?php endif ?>

I've changed a little your code, but basically the key line here is:

<img class="logo" src="<?= $logo ?>">

This, or the equivalent:

<img class="logo" src="<?php echo $logo ?>">

should show your image when the title is missing.


Bonus: If you're handling different thumbnail sizes I'd recommend you to use Image Array as Return Value. In that case, $logo would be an Array containing all information (such as sizes, all thumbnail URLs, captions, etc.)

Use:

<img class="logo" src="<?= $logo['sizes']['medium'] ?>">

where 'medium' is your thumbnail size label to output it.

Also, please check official docs on ACF's Image field type for more examples and further explanations.

like image 91
Jordi Nebot Avatar answered Oct 17 '22 21:10

Jordi Nebot