I am thinking about leveraging the wp_cron
and transients
.
You can create a helper function which will do the heavy lifting and do all the queries you need, but schedule it to be done like every 12 hours – twice daily (or more, depending on the frequency of new posts) using wp_cron
API.
Basically, this is what you need:
Helper function and WP cron job
/**
* Helper function to update tag transients with post IDs
*/
function wpse317707_update_tag_transients() {
$tags = get_tags(); // add args
/** @var WP_Term $tag */
foreach ( $tags as $tag ) {
// get random image for this tag
$args = array(
'post_type' => 'custom_event',
'tag__in' => array ( $tag->term_id ),
'posts_per_page' => -1,
);
$query = new WP_query ( $args );
$post_ids = wp_list_pluck( $query->posts, 'ID' );
set_transient( $tag->slug . '-tag-posts', $post_ids, DAY_IN_SECONDS );
}
}
add_action( 'update_tag_transients', 'wpse317707_update_tag_transients' );
/**
* Schedule WP Cron job
*/
if ( ! wp_next_scheduled( 'update_tag_transients' ) ) {
wp_schedule_event( time(), 'twicedaily', 'update_tag_transients' );
}
Your code, adjusted
$tags = get_tags( $args );
foreach ( $tags as $tag ) {
// get tag link
$tag_link = get_tag_link( $tag->term_id );
// get post IDs
$post_ids = get_transient( $tag->slug . '-tag-posts' );
// get random ID
$random_id = $post_ids[ array_rand( $post_ids, 1 ) ];
the_post_thumbnail( $random_id );
// display content
echo '<div id="tag-block">'
. $tag->name
. $tag->description
. '<a href="'.$tag_link.'">see tag archive</a>'
. '</div>';
}