How to return loop contents

There are replacements that return pure strings for all parts, no need to print anything into an output buffer. I like sprintf() and would write your example like this:

<?php
if ( $cms_pl_pages->have_posts() )
{
    $content="<section class="cms-pl-gallery">";
    while ( $cms_pl_pages->have_posts() )
    {
        $cms_pl_pages->the_post();
        $content .= sprintf(
            '<article class="cms-pl-item clearfix">
                %1$s
                <h2>
                    <a href="https://wordpress.stackexchange.com/questions/57000/%2$s" title="Read %3$s">%4$s</a>
                </h2>
                %5$s
            </article>',
            get_the_post_thumbnail(),
            apply_filters( 'the_permalink', get_permalink() ),
            the_title_attribute( array( 'echo' => FALSE ) ),
            the_title( '', '', FALSE ),
            has_excerpt() ? apply_filters( 'the_excerpt', get_the_excerpt() ) : ''
        );
    }
    $content .= '</section> <!-- end .cms-pl-gallery -->';
}
wp_reset_postdata();
return $content;

Leave a Comment