I have a custom post type and in the CPT’s single-cpt.php
file I would like to pull in two posts instead of one.
The two posts will be the post the user clicked in the relevant archive, and the next post in date order (i.e. the default post sorting method of WordPress). The reason for this is the posts are essentially small, useful pieces of information and having two posts pulled in will create a better SEO and user experience.
Normally when I want to pull in a set number of posts on an archive page I would use WP_Query()
and set 'posts_per_page' => 2
but out of the box this won’t work on a single-cpt.php
file because such code pulls in posts that are the most recent, not the post that was clicked on the archive page (and then the next most recent).
What I’m looking for is something that works with the WP loop so each post looks the same, but pulls in two posts (the selected one from the archive and then the next one in date order).
Note: If this isn’t possible with WP_Query() any other way to do it would be most welcome.
<?php
$newsArticles = new WP_Query(array(
'posts_per_page' => 2,
'post_type'=> 'news'
));
while( $newsArticles->have_posts()){
$newsArticles->the_post(); ?>
// HTML content goes here
<?php } ?>
<?php wp_reset_postdata(); ?>
Any help would be amazing.
3 Answers
Try this:
<?php
$current_id = get_the_ID();
$next_post = get_next_post();
$next_id = $next_post->ID;
$cpt = get_post_type();
$cpt_array = array($current_id, $next_id);
$args = array(
'post_type' => $cpt,
'post__in' => $cpt_array,
'order_by' => 'post_date',
'order' => 'ASC',
);
$the_query = new WP_Query($args);
if($the_query->have_posts()):
while($the_query->have_posts() ): $the_query->the_post();
echo '<h2>'.the_title().'</h2>';
endwhile;
endif;
wp_reset_postdata();
?>
Tested locally and seems to work fine.
get the current post id
get the next post id
get the current post post type
run query