Show Recent Posts For A Custom Post Type

I just used this on one of my client’s WordPress websites that needed a little pick me up. The task was to create a redirect page to send users to if a product was out of stock. In this case it was a dress. The client didn’t realize that sending a user to a dead page would do more harm to their SEO than they realized. So I built this page for them and added my snippet. Voila.

In this screenshot you can see the four rows of dresses below the search element. That’s this code working to display up to 8 dresses. The other 4 are below these. You can tell it to show however many you want. It’s up to you. The sky’s the limit.

Show Recent Posts WordPress Custom

For this I created a custom redirect and page template. I’ll be posting how to create a WordPress page template in another tutorial shortly. However, you can use this on your search results page as well. For this client it just made sense because it actually showed several new releases rather than made the user/customer do a search. It’s also a quicker way for the customer to get back into product pages.

Show Recent Posts For Custom Post Type

Add this code on whatever file you want. Wherever you or your client need to show recent posts for a particular custom post type. For my client I put it in on a page that I wanted to showcase if they came upon a dead link or 404 page. I always feel that page is never really designed right and could be done a lot better. For this my CPT is called “dress“. Change that to whatever yours is.

<?php
    $recent_posts = wp_get_recent_posts(array(
        'post_type'   =>'dress', //Change this to whatever your CPT is called
        'numberposts' => 8, // Number of recent posts thumbnails to display
        'post_status' => 'publish' // Show only the published posts
    ));
    foreach($recent_posts as $post) : ?>
        <li>
            <a href="<?php echo get_permalink($post['ID']) ?>">
                <?php echo get_the_post_thumbnail($post['ID'], 'full'); ?>
           </a>
        </li>
    <?php endforeach; wp_reset_query(); ?>

If the code no longer works or if you have questions please let me know.

Comments are held in moderation before posting. Please be patient with me as I am very busy. I don't allow any code to be added. I'll update the comment section soon to allow it though. All spam comments will be filtered out by WordPress automation. So don't even bother you little bot you.

Leave a Reply

Your email address will not be published. Required fields are marked *