I’m using the following PHP script to find the most recent post on the Team
area of my site.
I also use a very similar one to find the most recent news entry on my home page.
To reduce the amount of repeated code (DRY
), is there a way I can use a function and just pull in a specific custom post type e.g. most_recent('team');
would show the most recent post from my Team
CPT.
Here’s my existing code:
<?php
// find most recent post
$new_loop = new WP_Query( array(
'post_type' => 'team',
'posts_per_page' => 1,
"post_status"=>"publish"
));
?>
<?php if ( $new_loop->have_posts() ) : ?>
<?php while ( $new_loop->have_posts() ) : $new_loop->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php endwhile;?>
<?php else: ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
Yes, It is indeed possible.
First what you need to do is ,
Add below code to your theme’s
functions.php
file:Now you can use it any where in your theme folder template like below:
So in your case, it would be
most_recent('team')
or even you can use for other as well just like I did forproduct
.Tell me if you have any doubt.