I'm trying to get one post from today's date a year ago, and the code below is shown to be a slow query in Query Monitor. What is a more efficient way of querying for a post from a year before today's date?
<?php $args = array(
'date_query' => array(
'post_parent' => '',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'column' => 'post_date',
'before' => '1 year ago',
),
'posts_per_page' => 1,
);
$query = new WP_Query( $args ); ?>
<?php while($query->have_posts()) : $query->the_post(); ?>
<a href="<?php the_permalink() ?>">
<?php the_title(); ?></a>
<?php endwhile; wp_reset_postdata();?>
I'm trying to get one post from today's date a year ago, and the code below is shown to be a slow query in Query Monitor. What is a more efficient way of querying for a post from a year before today's date?
<?php $args = array(
'date_query' => array(
'post_parent' => '',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'column' => 'post_date',
'before' => '1 year ago',
),
'posts_per_page' => 1,
);
$query = new WP_Query( $args ); ?>
<?php while($query->have_posts()) : $query->the_post(); ?>
<a href="<?php the_permalink() ?>">
<?php the_title(); ?></a>
<?php endwhile; wp_reset_postdata();?>
Try below code. It will improve performance. First of all you have used below argument inside date_query instead of outside of date_query. It should be corrected.
I have removed before and instead used year, month, day.
References : WP_Query & WP_Date_Query
<?php
// Get the date for one year ago
$one_year_ago = date('Y-m-d', strtotime('-1 year'));
// Set up the WP_Query
$args = array(
'post_type' => 'post', // Can be changed to another post type if needed
'posts_per_page' => 1, // Number of posts to retrieve, -1 for all
'post_parent' => '',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'date_query' => array(
array(
'year' => date('Y', strtotime($one_year_ago)),
'month' => date('m', strtotime($one_year_ago)),
'day' => date('d', strtotime($one_year_ago)),
),
),
);
$query = new WP_Query( $args );
while($query->have_posts()) : $query->the_post();
?>
<a href="<?php the_permalink() ?>">
<?php the_title(); ?></a>
<?php endwhile; wp_reset_postdata();?>