So if you’ve registered a CPT called wpse_242473_custom_post_type
you can use this to put 6 recent posts of that type onto your static front page (or anywhere). You can use a shortcode or a template tag and the function should work for both.
It’s a modification of some code I use in a lot of sites. Put it in your theme’s functions.php
. Modify the HTML I’ve used to suit yourself, of course.
I’ve added a twist that I’ve been meaning to try for a while, so if it chokes on you let me know and I’ll test it properly. What I’ve added is a full set of optional arguments that let the same function work, I hope, for both a shortcode and a template tag. You can either put [recentposts]
into the visual editor on any page, or you can put <?php wpse_242473_recent_posts(); ?>
into any template of your theme.
To put it into the template for your static front page, edit (or create) the template front-page.php
. This will be automatically selected for your static front page, without you having to select it within the page edit screen.
function wpse_242473_recent_posts( $atts = null, $content = null, $tag = null ) {
$out="";
$args = array(
'numberposts' => '6',
'post_status' => 'publish',
'post_type' => 'wpse_242473_custom_post_type' ,
);
$recent = wp_get_recent_posts( $args );
if ( $recent ) {
$out .= '<section class="overview">';
$out .= '<h1>Recent Projects</h1>';
$out .= '<div class="overview">';
foreach ( $recent as $item ) {
$out .= '<a href="' . get_permalink( $item['ID'] ) . '">';
$out .= get_the_post_thumbnail( $item['ID'] );
$out .= '</a>';
}
$out .= '</div></section>';
}
if ( $tag ) {
return $out;
} else {
echo $out;
}
}
add_shortcode( 'recentposts', 'wpse_242473_recent_posts' );
It’s a straightforward retrieval of the posts you want.
The foreach
loop builds your HTML and then the conditional at the end either returns the HTML, if you’ve used a shortcode, or echoes it if your calling the function as a template tag.
What a lot of articles on the web don’t show you is that third argument passed to all shortcode handlers. When you use the shortcode it contains the shortcode name, so a handler could in theory handle multiple shortcodes. In this case we’re using it to tell whether the function was indeed called as a shortcode handler or not.