There’s not a real efficient way to do this. You’ll either have to make 3 queries or create your own SQL query and use global $wpdb;
. For simplicity purposes I’ve went with a 3 query approach.
If we know the slugs or IDs we can pass them to our tax query. Since the example code does not show that we need to run get_terms()
first to get the possible artists:
$artists = get_terms( array(
‘taxonomy’ => ‘artist’,
‘hide_empty’ => false,
) );
We can use get_posts()
to grab an Array of posts of a specific artist like so:
$art1_posts = get_posts( array(
'posts_per_page' => 1, // Only return 1 post
'orderby' => array( // Order by Date
'post_date' => DESC
),
'tax_query' => array( array( // Get first artist posts - inefficient
'taxonomy' => 'artists',
'field' => 'term_id',
'terms' => $artists[0]->term_id
) ),
'meta_key' => '_thumbnail_id', // Only return posts that have a post thumbnail
) );
The above is only an example since it’s using $artists[0]
. We instead want to loop through the available artists and store the results in a separate array. The final result could look something like this:
$featured_image_arr = array();
$artists = get_terms( array(
'taxonomy' => 'artist',
'hide_empty' => false,
) );
// If we have artists, loop through them, get the latest post, add to our featured image arr
if( ! empty( $artists ) ) {
foreach( $artists as $artist ) {
$artist_posts = get_posts( array(
'posts_per_page' => 1,
'orderby' => array(
'post_date' => DESC
),
'tax_query' => array( array(
'taxonomy' => 'artists',
'field' => 'term_id',
'terms' => $artist->term_id
) ),
'meta_key' => '_thumbnail_id',
) );
// Skip empty artists.
if( empty( $artist_posts ) ) {
continue;
}
$featured_image_arr[] = array(
'artist' => $artist,
'artist_post' => $artist_posts[0],
'thumbnail_id'=> get_post_meta( $artist_posts[0]->ID, '_thumbnail_id', true ),
'thumbnail_url'=> wp_get_attachment_image_url( $thumbnail_id, 'full' ),
);
}
}
// If we have featured images, show them.
if( ! empty( $featured_image_arr ) ) {
foreach( $featured_image_arr as $arr ) {
printf( '<div class="artistbox" style="background-image: url( %1$s )"><a href="https://wordpress.stackexchange.com/artists/%2$s">%3$s</a></div>',
$arr['thumbnail_url'],
$arr['artist']->slug,
$arr['artist']->name
);
}
}