I made a simple custom meta box plugin to display testimonials. I used a foreach loop to retrieve and display the data on my front-page.php page. However, using the exact same code on my page.php page returns
Warning: Invalid argument supplied for foreach().
What is the reason for this error and how can I fix it?
Here is the code used on both front-page.php and page.php:
<div id="testimonials">
<?php
$testimonials = get_post_meta($post->ID, "testimonials_data", true);
$counter = 0;
foreach($testimonials as $testimonial){
$counter++;
?>
<div class="testimonial <?php if($counter == 1){echo 'active-testimonial';}; ?>">
<p><?php echo $testimonial['field1']; ?></p>
<span><?php if(!empty($testimonial['field2'])){echo $testimonial['field2'];}; if(!empty($testimonial['field3'])){echo ' - ' . $testimonial['field3'];}; ?></span>
</div>
<?php }; ?>
</div>
EDIT: To be more clear. My problem isn't that the foreach loop doesn't work at all. It works on the front-page.php but not page.php using the same code. How do I get it to work on both pages?
Your get_post_meta() $single attribute is set to true. Try setting it to false so that it always returns an array.
$testimonials = get_post_meta($post->ID, "testimonials_data", false);
get_post_meta( int $post_id, string $key = '', bool $single = false )
This function return (mixed) values - It Will be an array if $single is false. - It Will be value of meta data field if $single is true.
so if you have stored value in string testimonials_data
except json_encoded. then it will show you value in array only.
and apply some !empty check
<div id="testimonials">
<?php
$testimonials = get_post_meta($post->ID, "testimonials_data", true);
$counter = 0;
if(!empty($testimonials)){
foreach($testimonials as $testimonial){
$counter++;
?>
<div class="testimonial <?php if($counter == 1){echo 'active-testimonial';}; ?>">
<p><?php echo $testimonial['field1']; ?></p>
<span><?php if(!empty($testimonial['field2'])){echo $testimonial['field2'];}; if(!empty($testimonial['field3'])){echo ' - ' . $testimonial['field3'];}; ?></span>
</div>
<?php };
}?>
</div>