Default to most recent image

The `genesis_get_image()` function in Genesis is smart. If you specify a featured image, it uses that. If you don’t, it uses the first image you uploaded to that post instead of displaying nothing.

But in some instances you might find the most recent image is more useful. You might be updating a post over time with updates, and want the featured image to always be the most recent.

The code below changes the Genesis default to ‘last uploaded’ rather than ‘first uploaded’. If you specify a featured image, that will always be used.

<?php

/**
 * Default to most recent image 
 *
 * @author Bill Erickson
 * @link https://www.billerickson.net/code/default-to-most-recent-image
 *
 * @param array $defaults
 * @param array $args
 * @return array $defaults
 */
function ea_default_to_most_recent_image( $defaults, $args ) {

	$image_ids = array_keys(
		get_children(
			array(
				'post_parent'    => isset( $args['post_id'] ) ? $args['post_id'] : get_the_ID(),
				'post_type'	     => 'attachment',
				'post_mime_type' => 'image',
				'orderby'        => 'menu_order',
				'order'	         => 'ASC',
			)
		)
	);
	
	$defaults['num'] = key( array_slice( $image_ids, -1, 1, TRUE ) );

	return $defaults;
}
add_filter( 'genesis_get_image_default_args', 'ea_default_to_most_recent_image', 10, 2 );

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk