'How can I use query_posts to filter posts from a specific year?
How can I use the query_posts functions within Wordpress to filter my posts out by a specific year?
Here's my current code:
<?php query_posts('cat=3&posts_per_page=10');
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
<a href="<?php the_permalink(); ?>">
<div class="testpost">
<?php the_post_thumbnail(); ?>
<h4><?php the_title(); ?></h4>
<hr class="smallblue">
<h5><?php the_time(); ?></h5>
<h6><?php echo get_the_date(); ?></h6>
</div>
</a>
<?php
endwhile; endif; >
wp_reset_query();
?>
Solution 1:[1]
You can use the date_query argument of WP_Query, which has the advantage of being slightly more readable:
$args = array(
'cat' => 3,
'posts_per_page' => 10,
'date_query' => array(
array(
'year' => 2017,
),
),
);
$myQuery = new WP_Query($args);
// Or $myQuery = get_posts($args);
if ($myQuery->have_posts()) :
while ($myQuery->have_posts()) : $myQuery->the_post();
// Output
endwhile;
endif;
But please: never, ever use query_posts. It should only ever be used by the core. Use one of the many, many other functions available like WP_Query or get_posts, where the same array of arguments can be used safely.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gilad905 |
