Fredmat
Fredmat

Reputation: 958

WP_Query expiration date

I have a custom post type that will be shown in frontend of my WordPress. When I make a query with WP_Query I'd like to select posts that are not older then 30 days.

I know that it exist plugins for that, but I don't want to use plugins at all for my project.

I also tried with post meta (yes it works), but I really want to know if it is possible to play with the post date in the query itself?

My (basic) query:

$data = new WP_Query(
    array(
        'post_type' => array( 'my-cpt' ),
        'post_status' => array( 'publish' ),
        'posts_per_page' => 1,
        'nopaging' => true,
        'orderby' => 'date',
        'order' => 'DESC',
        'paged' => $paged,
        // Don't want the following ...
        // 'meta_key' => ' expiration_time',
        // 'meta_value' => current_time( 'timestamp', 0 ),
        // 'meta_compare' => '>='
    )
);

Upvotes: 1

Views: 802

Answers (1)

Howli
Howli

Reputation: 12469

This should work, adding "date_query" to the query should limit the results to within the last 30 days.

$data = new WP_Query(
array(
    'post_type' => array( 'my-cpt' ),
    'post_status' => array( 'publish' ),
    'posts_per_page' => 1,
    'nopaging' => true,
    'orderby' => 'date',
    'order' => 'DESC',
    'paged' => $paged,
    'date_query' => array(
        'after' => date('Y-m-d', strtotime('-30 days')) 

)
);

Upvotes: 1

Related Questions