我正在考虑利用wp_cron
和transients
.
您可以创建一个助手函数,该函数将完成繁重的工作并执行所有需要的查询,但可以使用wp_cron
API。
基本上,这就是您需要的:
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>\';
}