2017-07-21 26 views
0

如何在Wordpress中使用query_posts函數來過濾特定年份的帖子?如何使用query_posts過濾特定年份的帖子?

這裏是我當前的代碼:

<?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(); 
?> 
+0

請永遠不要*使用'query_posts'(參考:stackoverflow.com/a/25589475/988246)。它應該只能被核心使用。使用諸如'WP_Query'或'get_posts'等許多其他可用函數之一,其中可以安全地使用相同的參數數組。 – indextwo

回答

1
<?php query_posts('cat=3&posts_per_page=10&year=2004'); ?> 

年傳遞給查詢

+0

就是這樣,謝謝! –

+0

歡迎您@GrantAb – Exprator

1

可以使用date_query說法WP_Query,其中有稍微更具可讀性的優點是:

$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 

    enwhile; 
endif; 

但請:never, ever use query_posts。它應該只能被核心使用。使用WP_Queryget_posts等許多其他功能中的一種,其中可以安全使用相同的參數數組。

+0

謝謝我會進一步研究。讚賞。 –

相關問題