I am creating an array of items in the header that will be called in the index file of a WordPress template. But for some reason I am getting:
Notice: Undefined variable: img_arr in ... on line 27
Why is this happening when in my header I define it:
$img_arr = array();
$caption_arr = array();
// Second Featured Image
if (class_exists('MultiPostThumbnails')) {
$image_name = "second-image";
if (MultiPostThumbnails::has_post_thumbnail('page', $image_name)) {
$image_id = MultiPostThumbnails::get_post_thumbnail_id( 'page', $image_name, $post->ID );
$attr = array('class' => "featured-image");
$image_2 = wp_get_attachment_image( $image_id, 'second-image', false, $attr );
array_push($img_arr, $image_2);
}
};
$post_thumbnail_id = MultiPostThumbnails::get_post_thumbnail_id( get_post_type(), 'second-image', get_queried_object_id() );
$post_thumbnail_post = get_post( $post_thumbnail_id );
$caption_2 = trim( strip_tags( $post_thumbnail_post->post_excerpt ) );
array_push($caption_arr, $caption_2);
This allows users to add multiple featured images, all the way up to ten images. But it goes unrecognized in the index file:
foreach($img_arr as $key => $value) {
echo $value;
echo '<div class="featured-image-caption">';
echo $caption[$key];
echo '</div>';
}
I’ve been working on this for many hours, so I may be overlooking something very simple. Or is it possible that the WordPress function get_header()
doesn’t allow arrays to move between files? And if so, is there something I could add to my functions.php
to allow arrays to be more global?
I am pretty sure that the WordPress API structure does not allow you to pass variables or arrays the way you think it work work with straight PHP. So instead, consider using a
global
variable scope to achieve the goals of this function:So in your index file you could do something like this:
Or you could do it with
$GLOBALS
:And then access the values like this:
Also you do this to initialize the arrays:
Which means itâs starting from scratch, right?
Then why are you doing this:
Wny not just do a simple increment of the array like this: