最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - How to show optimized list of posts with all their attachment images

programmeradmin0浏览0评论

In page-images.php template I have created this code which displays a list of posts which belong to a category and order them by meta value. So basically it is like a category page, generally nothing special except that each post isn't shown as a single featured image but with all its images like this: This code works but I ask myself how can it be more optimized? Since it has nested WP_Query. Page generates 100 queries and it should be a paginated list like this for each category and for many variations (depending on meta key).

$query = new WP_Query( array(
    'posts_per_page' => 25, 
    'cat' => 102, // Category ID
    'meta_key' => 'rod', // Order by meta field value
    'orderby'   => 'meta_value',
    'order' => 'ASC',
    'post_status' => 'publish',
    'meta_query' => array( // Meta value should exists
            array(
                'key' => 'rod',
                'value'   => array(''),
                'compare' => 'NOT IN'
            )
        )
    ));

// Inside loop for each post get its images
if ($query->have_posts() ) {
    while($query->have_posts()) {
    $query->the_post();

        $args = array(
            'posts_per_page' => -1, 
            'post_type' => 'attachment',
            'post_mime_type' => 'image',
            'post_status' => 'any', 
            'post_parent' => get_the_ID(),
            'order' => 'DESC'
            );
        $attachments = new WP_Query($args);
            ?>


        <div class="col-md-10">
            <?php // each loop has a title, meta field and images
            <h2><?php echo get_the_title($key); ?></h2>
            <p><?php the_field('latinsko_ime', $key); ?></p>

            <div class="row">
                <?php while($attachments->have_posts()) : $attachments->the_post(); ?>
                <div class="col-md-3">

                    <a href="<?php the_permalink(); ?>">
                        <?php echo wp_get_attachment_image(get_the_ID(), 'category__loop', false, array('class' => 'img-fluid')); ?>
                    </a>

                </div>
                <?php endwhile; ?>
            </div>

        </div>

    <?php 
    }

}

I have tried removing nested WP_Query and for each loop retrieve images like this $gallery = get_post_gallery_images( get_the_ID() ); but in this case I have even more queries (127)

发布评论

评论列表(0)

  1. 暂无评论