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
2
Answers
you can use these two keys before and after rather than Compare
The
wp_posts
table has an index on(post_type, post_status, post_date,ID)
. If you only query by date you can’t exploit that index, and your query may have to look at the entire table (which is large in your case).You might try querying for only published posts. What you call blogs are called posts in WordPress parlance. That may allow the MySQL database to exploit the index. You could try this query (not debugged):
It will be hard to help you further until you use the Query Monitor plugin to investigate the slow query.