Can't you do this in HTML? So instead of printing everything in your loop, append it to a string that you print in the end. That way you can keep special stuff apart.
I assume this is a follow-up question to your previous question about featured images, so I will use the code from my answer there as an example.
<?php
$testimonials = get_posts( array(
'category_name' => 'testimonial',
'numberposts' => -1,
'order' => 'DESC'
) );
$highlighted_testimonial_thumbnail = '';
$other_testimonial_thumbnails = '';
foreach ( $testimonials as $testimonial ) {
if ( $testimonial->ID == $current_testimonial_id ) {
$highlighted_testimonial_thumbnail = '<li class="highlighted">' . get_the_post_thumbnail( $testimonial->ID, 'nav' ) . '</li>';
} else {
$other_testimonial_thumbnails .= '<li>' . get_the_post_thumbnail( $testimonial->ID, 'nav' ) . '</li>';
}
}
echo '<ul class="portfolio">';
echo $highlighted_testimonial_thumbnail;
echo $other_testimonial_thumbnails;
echo '</ul>';
Or more generic: instead of:
foreach ( $array_of_stuff as $stuff ) {
echo $stuff
}
Do it like this:
$output = '';
$featured_output = '';
foreach ( $array_of_stuff as $stuff ) {
if ( is_featured( $stuff ) ) {
$featured_output = $stuff;
} else {
$output .= $stuff;
}
}
echo $featured_output;
echo $output;
Almost all functions in WordPress that echo something have an equivalent that doesn't echo but just returns it. get_the_content()
vs the_content()
for example.