foreach loop – repeat foreach or store/echo result for second loop

This is regarding filtering the native gallery output for WordPress from answer: here

// Now you loop through each attachment
foreach ($attachments as $id => $attachment) {
// Fetch all data related to attachment 
$img = wp_prepare_attachment_for_js($id);

// If you want a different size change 'large' to eg. 'medium'
$url = $img['sizes']['large']['url'];
$height = $img['sizes']['large']['height'];
$width = $img['sizes']['large']['width'];
$alt = $img['alt'];

// Store the caption
$caption = $img['caption'];

$output .= "<li>n";
$output .= "<img src="{$url}" width="{$width}" height="{$height}" alt="{$alt}" />n";

// Output the caption if it exists
if ($caption) { 
    $output .= "<div class="orbit-caption">{$caption}</div>n";
}

$output .= "</li>n";
}

$output .= "</ul>n";
$output .= "</div>n";

return $output;

}

Is there a more efficient way of repeating the foreach loop output if the results are required again, rather than just repeating the foreach loop?

Read More

(Could use a different variable in foreach loop, but then not sure if it seems logical to disrupt concatenated output.)

Would appreciate logic or approach for insight.

Related posts

1 comment

  1. You don’t have to return $output inside the foreach like in a function. You can use the variable outside the loop on the same accesslevel.

Comments are closed.