Support » Developing with WordPress » Display last week’s posts (PHP)

  • I use this function I found from wpbeginner.com to display the last week’s posts in a wordpress page.

    function wpb_this_week() {
    $week = date('W');
    $year = date('Y');
    $the_query = new WP_Query( 'year=' . $year . '&w=' . $week );
    if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?> "><?php the_title(); ?></a></h2>
    	<?php the_excerpt(); ?>
      <?php endwhile; ?>
      <?php wp_reset_postdata(); ?>
    <?php else:  ?>
      <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif;
    }
    add_shortcode('semaine', 'wpb_this_week');

    This code worked for a few years but recently I have noticed that it always return “sorry, no posts matched” error message. I haven’t edited the code recently so I assume a wordpress update broke it.

    I would appreciate some help understanding what’s wrong with this line using the latest WordPress version:
    $the_query = new WP_Query( 'year=' . $year . '&w=' . $week );

    Thanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Samuel Wood (Otto)

    (@otto42)

    WordPress.org Admin

    There is nothing wrong with that code.

    Do you not have any posts from that week?

    Moderator bcworkz

    (@bcworkz)

    If you are sure posts in that week exist, some other code is probably corrupting the query, likely through the “pre_get_posts” action. After instantiating a new query object, output $the_query->request, which is the WP query’s eventual SQL query. Examine the WHERE clause for reasons why no posts are being returned.

    Hopefully the reason will be a good clue towards finding and correcting the corrupting code. If all else fails, you could add code to override what ever the corruption is.

    You might try changing the query to use the date_query option instead of the string.

    Try this code,

    
    function wpb_this_week() {
    $week = date('W');
    $year = date('Y');
    
     $args = array(
    	'date_query' => array (
    		'year' => $year,
    		'week' => $week
    	)
     );
    
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?> "><?php the_title(); ?></a></h2>
    	<?php the_excerpt(); ?>
      <?php endwhile; ?>
      <?php wp_reset_postdata(); ?>
    <?php else:  ?>
      <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif;
    }
    add_shortcode('semaine', 'wpb_this_week');
    
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Display last week’s posts (PHP)’ is closed to new replies.