How to optimize posts query in wordpress

Question

basically, I’m trying to optimize this query we have more than 100K blogs and I need to make it faster now it takes Load time (07.46 s).

<?php
                    if ( get_query_var( 'paged' ) ) { $paged = get_query_var( 'paged' ); }
                    elseif ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }
                    else { $paged = 1; }
                            $query = new WP_Query(array(
                                'date_query' => array(
                                        array(
                                                'year' => date( 'Y' )-2,
                                                'compare'   => '>=',
                                        ),
                                ),
                                'posts_per_page'   => 10,
                                'paged' => $paged
                            ));
                            while ($query->have_posts()): $query->the_post(); ?>
                    <article id="post-<?php the_id() ?>" class="card bg-light text-dark card-blog">

                        <?php the_post_thumbnail('large',['class'=>'card-img-top']); ?>

                        <div class="card-body">
                            <span class="card-meta">
                                <time datetime="<?php echo strtotime(the_time('F j, Y')); ?>"><?php echo the_time('F j, Y'); ?></time> | <?php the_category(', '); ?>
                            </span>
                            <h3 class="card-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                            <p class="lead"><?php  echo substr(get_the_excerpt(),0,50).'...'; ?></p>
                            <div class="btn-container">
                                <a href="<?php the_permalink(); ?>" class="btn btn-primary">Learn More<?php gpi_sprite('arrow-right'); ?></a>
                            </div>
                        </div>
                    </article>
                    <?php endwhile; ?>
                </div>
            </section>
                <?php
                    $pages = paginate_links( array(
                        'format' => '?page=%#%',
                        'current' => max( 1, get_query_var('page') ),
                        'total' => $query->max_num_pages,
                        'type'=>'array',
                    ) );
                ?>

the above query grabbing all blog posts 10 posts per page but I show only the latest 2 years and this takes much expected than I imagine I appreciate any help

in progress 0
Mohamed Mazen 2 months 2021-08-05T10:22:43-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-08-05T12:43:01-05:00

    Is this the primary query on the page? Is there a reason you’re not using pre_get_posts? By doing it on the page you’re doubling the number of queries as you’re throwing away the main query

Leave an answer

Browse
Browse