1

I'm trying to make a page with multiple loops. I need each loop to display posts from a particular category. One category after another.

At the moment I have the loop below displaying posts from a category named "one". To display posts from category "two" and so on, I'm repeating the entire loop just changing the category_name.

I imagine that this is a very bad approach taking into consideration the DRY principle and resources usage. However, I can't figure out a smarter way to write this loop.

$posts = get_posts(array(
    'posts_per_page'    => -1,
    'post_type'         => 'post',
    'category_name'     => 'one',
    'orderby'           => 'rand'
));

if ($posts) : ?>

    <div class="dt-loop-container">

        <?php foreach ($posts as $post) :

            setup_postdata($post);

        ?>

            <div class="dt-loop-item">
                <div class="dt-loop-logo">
                    <?php if (get_field('logo')) : ?>
                        <img src="<?php the_field('logo'); ?>" alt="Logo">
                    <?php endif; ?>
                </div>
                <h3 class="dt-loop-title">
                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                </h3>
                <ul class="dt-loop-especialidades">
                    <?php if (get_field('especialidade_1')) : ?>
                        <li><?php the_field('especialidade_1'); ?></li>
                    <?php endif; ?>
                    <?php if (get_field('especialidade_2')) : ?>
                        <li><?php the_field('especialidade_2'); ?></li>
                    <?php endif; ?>
                    <?php if (get_field('especialidade_2')) : ?>
                        <li><?php the_field('especialidade_3'); ?></li>
                    <?php endif; ?>
                </ul>
            </div>

        <?php endforeach; ?>

    </div>

    <?php wp_reset_postdata(); ?>

<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.