Pull In Two Posts To Custom Post Type `cpt-single.php` File With WP_Query()
-
Hi,
I have a custom post type and in the CPT’s
cpt-single.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 cpt-single.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).
<?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.
Emily
- The topic ‘Pull In Two Posts To Custom Post Type `cpt-single.php` File With WP_Query()’ is closed to new replies.