Skip to content

Instantly share code, notes, and snippets.

@YFilus
Last active February 8, 2021 18:01
Show Gist options
  • Select an option

  • Save YFilus/0d2290cc1611b378a71a8843e66524fb to your computer and use it in GitHub Desktop.

Select an option

Save YFilus/0d2290cc1611b378a71a8843e66524fb to your computer and use it in GitHub Desktop.
WordPress - Cache wp_oembed_get
<?php
// from https://snippets.khromov.se/how-to-cache-the-wp_oembed_get-function/
define('CUSTOM_OEMBED_CACHE_KEY', 'coc_');
function _wp_custom_oembed_cache_key($url, $args) {
$args_serialized = serialize($args);
return CUSTOM_OEMBED_CACHE_KEY . md5("{$url}-{$args_serialized}");
}
add_filter('oembed_result', function($data, $url, $args) {
// Cache result
set_transient(_wp_custom_oembed_cache_key($url, $args), $data, DAY_IN_SECONDS);
return $data;
}, 999, 3);
add_filter('pre_oembed_result', function($result, $url, $args) {
// Clean out empty oembed calls caused by Divi
if(trim($url) === '') {
return '';
}
// Return cached result if available
if($cached_result = get_transient(_wp_custom_oembed_cache_key($url, $args))) {
return $cached_result;
}
return $result;
}, 2, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment