2

How can I create a feed which is just the previous 24 hours posts? or is that even possible? are there plugins that offer the functionality?

1 Answer 1

4

Alright kids, we're gonna leverage a couple of awesome WordPress features today. First things first, let's get that custom feed registered with add_feed:

/**
 * Register "my_feed".
 */
function wpse_226681_register_feed() {
    // do_feed_rss() loads the default RSS template in WordPress
    add_feed( 'my_feed', 'do_feed_rss' );
}

add_action( 'init', 'wpse_226681_register_feed' );

/**
 * Handle content-type for "my_feed".
 */
function wpse_226282_feed_type( $type, $name ) {
    if ( $name === 'my_feed' )
        $type = feed_content_type( 'rss2' );

    return $type;
}

add_filter( 'feed_content_type', 'wpse_226282_feed_type', 10, 2 );

... where my_feed is the name of your feed i.e. example.com/feed/my_feed. Make sure to flush your rewrite rules once the code is in place - just re-save your permalink settings in the admin.

Next we need to override the default query for our custom feed - we'll be using a date query to get all posts within the last 24 hours:

function wpse_226681_feed_query( $wp_query ) {
    if ( $wp_query->is_main_query() && $wp_query->is_feed( 'my_feed' ) ) {

        $wp_query->set( 'ignore_sticky_posts', true );
        $wp_query->set( 'posts_per_page', -1 );
        $wp_query->set( 'date_query', [
            'after' => date( 'Y-m-d H:i', strtotime( '-24 hours' ) ),
        ]);

    }
}

add_action( 'pre_get_posts', 'wpse_226681_feed_query' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.