I wanted to display the featured image (post thumbnail) of one post from the most latest blog posts.
I didn’t want a plugin as the image was being displayed in some custom header background code… that at the top of the home page of this site.
I couldn’t find any code online that I could copy and paste and with a few similar recent and random post code snippets, I created my own PHP code snippet to display the featured image of one post from the latest X posts.
The code below uses the WordPress wp_get_recent_posts() function using appropriate arguments in the $arg variable to retrieve the most recent 30 posts.
Then, one random post is found that contains an featured image, as not all my posts contain a featured image.
Once the random post containing a featured image is found, the featured image URL is displayed.
You may wish to display other aspects of the post including the title and content, and these are contained the $onepost array which contains the following variables and their values for the one random post.
[ID] [post_author] [post_date] [post_date_gmt] [post_content] [post_title] [post_excerpt] [post_status] [comment_status] [ping_status] [post_password] [post_name] [to_ping] [pinged] [post_modified] [post_modified_gmt] [post_content_filtered] [post_parent] [guid] [menu_order] [post_type] [post_mime_type] [comment_count] [filter]
Note that the featured image URL is not a variable in the $onepost array, and I used the WordPress function get_post_thumbnail_id() with the one random post ID to retrieve the one featured image URL.
The PHP code to get 1 random WordPress post from recent X posts.
$numberofposts = 30; $args = array( 'numberposts' => $numberofposts, 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true ); $recent_posts = wp_get_recent_posts( $args ); $randompost = rand(0,($numberofposts-1)); $onepost = $recent_posts[$randompost]; while ( !has_post_thumbnail($onepost['ID']) ) { $randompost = rand(0,($numberofposts-1)); $onepost = $recent_posts[$randompost]; } echo wp_get_attachment_url( get_post_thumbnail_id($onepost['ID']) );
Leave a Reply