Finding the next 5 posts

The integral part is using a date_query in a custom WP_Query to fetch the adjacent posts according to the parameters passed to it. Here is an idea coming from a plugin I’m busy with

To accomplish what you need, you’ll need the following

  • The current post object to get the post_date and ID

  • The categories assigned to the current post.

The first part can be accomplished with get_queried_object() which will hold the post_date and ID. The latter part can be accomplished with wp_get_post_terms() for effiency

Putting it all together, you can try the following: (CAVEAT: This is all untested and might be buggy, posting from a tablet)

$post_object = get_queried_object();
$terms = wp_get_post_terms( $post_object->ID, 'category', array( 'fields' => 'ids' ) ); // Set fields to get only term ID's to make this more effient

$args = array(
    'cat' => $terms[0],
    'posts_per_page' => 5,
    'no_found_rows' => true,   // Get 5 poss and bail. Make our query more effiecient
    'suppress_filters' => true,  // We don't want any filters to alter this query
    'date_query' => array(
        array(
            'after' => $post_object->post_date,  // Get posts after the current post, use current post post_date
            'inclusive' => false, // Don't include the current post in the query
        )
    ) 
);
$q = new WP_Query( $args );
var_dump( $q->posts );

FEW IMPORTANT NOTES

  • You need to play around with after and before in your date_query and with the order parameter. I cannot remember from the top of my head how I put this piece togther, shame on me. I think if you use before in your date_query, you need to set order to ASC to get the correct posts. But as I said, play around with those parameters

  • I have used the default taxonomy category in my example. If you are using a custom taxonomy, change category in wp_get_post_terms() to your desired taxonomy name. Also, remove the cat parameter in the query arguments and replace it with a proper tax_query

  • If you are only interested in getting post ID’s, then you can set 'fields' => 'ids' in your query arguments to make your query more effient as well

This should give you a basic idea and this should help you to achieve your goal

Leave a Comment