I’ve built an array of image URLs on a WordPress template page like this:
<?php $attachments = get_posts(array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
));
if ($attachments) {
//set up array of urls
$image_urls = array();
foreach($attachments as $attachment){
$image_object = wp_get_attachment_image_src($attachment->ID,'full');
$image_urls[] = $image_object[0];
}
} ?>
Then, in footer.php, I’d like to print the array for Javascript like this:
<script>
var images = [<?php $num_urls = count($image_urls);
$num = 1;
foreach($image_urls as $image_url) {
echo $image_url;
$num++;
if($num<$num_urls) echo ', ';
} ?>];
</script>
I mistakenly assumed that, in concatenating the template page and footer.php, PHP would view the script as continuous, and remember the variable value, but that’s not the case, as it returns:
Warning: Invalid argument supplied for foreach()
How do I declare that $image_urls array so that I can refer to it later, without a scoping/namespacing danger?
PS Is there a better way to add a comma after all but the last item in the latter piece of code?
It should, unless WordPress is odd this way, or unless the variable is inside a function scope (in either file). If so, add this declaration:
at the top of the function(s). Alternatively, reference $image_urls everywhere via $GLOBALS. E.g.,
Use the implode function:
I think you need quotes around each item too, so:
Or, in general, I’d do something like this for that type of loop: