Ask your WordPress questions! Pay money and get answers fast! (more info)

Getting an error with IF statement and ACF repeater field WordPress

  • SOLVED

I'm trying to only show an Advanced Custom Fields repeater field if someone selects a Yes checkbox. It worked on my VPS, but it's throwing an error on the shared host.



<?php

$values = get_field('show_social_media_icons_at_the_top',2);

if(in_array("Yes", $values )){
?>

<?php while( have_rows('social_media',2) ): the_row();
$icon = get_sub_field('social_media_icon');
$label = get_sub_field('social_media_label');
$link = get_sub_field('social_media_link');

?>
<div class="top-social-icon"><a href="<?php echo $link; ?>" target="_blank"><img src="<?php echo $icon; ?>" alt="<?php echo $label; ?>"></a></div>

<?php endwhile; ?>

<?php
}

?>



If I check the Yes box, it works fine on the host, but if I leave it unchecked, the following happens:

Warning: in_array() expects parameter 2 to be array, string given in /home/bewell36/public_html/wp-content/themes/oily-sites/templates/header.php on line 118



Answers (2)

2015-08-01

Andrea P answers:

the ACF checkbox is treated as a string if it's NULL.

just add a conditional to check if the value is an array (if it's not an array, means it's empty and you don't have anything to loop).


<?php
$values = get_field('show_social_media_icons_at_the_top',2);

if (is_array($values)){
if(in_array("Yes", $values )){

?>



<?php while( have_rows('social_media',2) ): the_row();

$icon = get_sub_field('social_media_icon');

$label = get_sub_field('social_media_label');

$link = get_sub_field('social_media_link');



?>

<div class="top-social-icon"><a href="<?php echo $link; ?>" target="_blank"><img src="<?php echo $icon; ?>" alt="<?php echo $label; ?>"></a></div>



<?php endwhile; ?>



<?php

}
}
?>


Kyler Boudreau comments:

Andrea,

You rock. That fixed it!

2015-08-01

Jeremy answers:

Have you confirmed that $values is indeed an array?

echo "<pre>";
print_r($values);
echo "</pre>";


Or test $values

echo is_array($values) ? 'Array' : 'not an Array';


Kyler Boudreau comments:

Jeremy,

It says "No an Array." What does that mean?


Jeremy comments:

That would be why you are getting the error "Warning: in_array() expects parameter 2 to be array, string given"

Try the following:

$values = get_field('show_social_media_icons_at_the_top',2);

if( $values ) {

echo $values;

} else {

echo 'empty';

}


What does it output?


Kyler Boudreau comments:

That gives me:

$values = get_field('show_social_media_icons_at_the_top',2); if( $values ) { echo $values; } else { echo 'empty'; }