PHP if / else get_field () with WordPress

I am trying to give the client some options in the WP backend to configure the carousel that appears on the home page of my site. I use Advanced Custom Fields to process input from the client. I want to give them two options:

Option # 1) Allows the client to insert a line of text to display ('carousel_title_text')

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

I want the code to check the title text, and if not, display the logo. I have not yet decided what will happen if both fields are empty. Anyway, this is what I came 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');
}
?>

"carousel_title_text" is displayed as long as there is an input, but when it is empty, and "carousel_logo" is not, it displays the logo incorrectly. Can someone tell me what I'm doing wrong or if there is a better approach?

Thanks in advance,

+4
source share
3 answers

You have an else else condition that will be displayed by default if the client does not enter text with a logo. You will use the following code.

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

the default client by default indicates that it did not enter slider text

Hope it works for you.

0
source

Try:

<?php 
 $output = (get_field('carousel_title_text')) ? get_field('carousel_title_text'):get_field('carousel_logo');

 echo $output;
?>
0
source

, If/Else, . , (carousel_logo) ACF.

:

Return Values ​​for Image Fields

.. ACF Image Image Array, .

, the_field('carousel_logo'); . , ?

, URL- :

<?
$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 ?>

, :

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

:

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

, .


Bonus: If you work with different sizes of thumbnails, I would recommend using Image Array as the return value. In this case, it $logowill be an array containing all the information (for example, sizes, all sketches, titles, etc.).

Using:

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

where 'medium'is your sketch size to display it.

Also, please check the white papers for the ACF Image field type for more examples and further explanations.

0
source

All Articles