1

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(); ?>

2 Answers 2

1
<?php
function most_recent($type) {
    $new_loop = new WP_Query( array(
    'post_type' => $type,
        'posts_per_page' => 1,
        "post_status"=>"publish"
    ));


if ( $new_loop->have_posts() ) {
    while ( $new_loop->have_posts() ) : $new_loop->the_post();

          echo '<h2>'.the_title().'</h2>';

          the_content();

    endwhile;
}
wp_reset_query();
}
?>
Sign up to request clarification or add additional context in comments.

2 Comments

With a bit of work, that worked perfectly. Now it seems super obvious : ) I changed line 3 to read 'post_type' => $type,
Woops, sorry about that! Trying to answer two questions at once. Post has been edited.
1

Yes, It is indeed possible.

First what you need to do is ,

Add below code to your theme's functions.php file:

function most_recent($name){

    // find most recent post
    $new_loop = new WP_Query( array(
                        'post_type' => $name,
                        'posts_per_page' => 1,
                        "post_status"=>"publish"
                ));

    if ( $new_loop->have_posts() ) :
        while ( $new_loop->have_posts() ) : $new_loop->the_post();

          echo "<h2>".the_title()."</h2>";
          the_content();

            endwhile;
    else:
    endif;
    wp_reset_query();
}

Now you can use it any where in your theme folder template like below:

 $most_recent = most_recent('product');
 echo $most_recent;

So in your case, it would be most_recent('team') or even you can use for other as well just like I did for product.

Tell me if you have any doubt.

2 Comments

Many thanks for your answer & detailed response. I found it very helpful :)
Glad that You found it helpful :) Happy Coding !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.