The Transient API may help you here. A transient is variable stored for a defined amount of time.
function filemtime_remote( $url )
{
$list = file_get_contents( $url , null , null , 0 , 200);
$important = explode("Last modified: ",$list)[1];
$mydate = substr($important, 0, 21);
return $mydate;
}
The above is your current code which seeks the “Last modified” time each time a page is loaded.
You can convert it to:
function filemtime_remote( $url ){
# Get the transient
$mydate = get_transient( 'lm_' . esc_url( $url ) );
if( false === $mydate ) {
# The transient expired or does not exist, so we fetch the last modified again
$list = file_get_contents( $url , null , null , 0 , 200);
$important = explode("Last modified: ",$list)[1];
$mydate = substr($important, 0, 21);
# We then save that date in a transient(which we can prefix with something like "lm_")
# We are saving the transient for 12 hours
set_transient( 'lm_' . esc_url( $url ), $mydate , 12 * HOUR_IN_SECONDS );
}
return $mydate;
}
I haven’t tried it, but the logic is here: Use get_transient()
to see if we have a value recorded with the last 12 hours. If we do have a value (the returned value will not be FALSE
), use that value. If we do not have a value(the returned value will be FALSE
), then request the data and then save it in a transient, using set_transient()
, that will expire in 12 hours.