WordPress Function – fix to stop repeating code

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.

Read More

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

Related posts

Leave a Reply

2 comments

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