• Resolved Libin

    (@libinvbabu)


    I’m trying to fetch posts from current week.

    <?php
        $args = array(
            'date_query' => array(
                array(
                    'year' => date( 'Y' ),
                     'week' => date( 'W' ),
                ),
            ),
            'post_type' => 'stars', 'posts_per_page' => 99, 'order' => 'DEC',
        );
        $loop = new WP_Query( $args );
    ?>

    This code is fetching the posts from Monday to Sunday (Start day of my week is “Monday” in general settings.) But when I changed the start date of week to “Sunday” in the general settings, the above code is not fetching any posts.

    I referred to this codex and it leads me to this MySQL function. But I’m not sure how to implement that in my query.

    Any ideas?

Viewing 2 replies - 1 through 2 (of 2 total)
  • You should not need to change anything with the MySQL code. The WP_Query code should be handling the difference properly.

    If you add a print_r just after the new WP_QUERY() line, like this:

    $loop = new WP_Query( $args );
    print_r("<pre>REQUEST: $loop->request</pre>");

    then you should see this in the request for start of week = Sunday: WEEK( post_date, 0 )

    If you set start of week = Monday, you should see this: WEEK( post_date, 1 )

    That indicates that the proper mode is being sent to MySQL.

    Thread Starter Libin

    (@libinvbabu)

    Found the solution.

    changing 'week' => date( 'W' ), to 'week' => strftime( '%U' ), fixed the problem.

    where %U is:

    Week number of the given year, starting with the first Sunday as the first week

    Final code:

    <?php
        $args = array(
            'date_query' => array(
                array(
                    'year' => date( 'Y' ),
                    'week' => strftime( '%U' ),
                ),
            ),
            'post_type' => 'stars', 'posts_per_page' => 99, 'order' => 'DEC',
        );
        $loop = new WP_Query( $args );
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to show posts from current week (Sunday to Saturday)’ is closed to new replies.