Skip to content

Instantly share code, notes, and snippets.

@jmarreros
Created November 3, 2020 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmarreros/4f284a3ec16fae4ae8880bc6ef9809ef to your computer and use it in GitHub Desktop.
Save jmarreros/4f284a3ec16fae4ae8880bc6ef9809ef to your computer and use it in GitHub Desktop.
Ejemplo de recuperación de datos de entradas relacionadas desde la cache de objetos en WordPress
<?php // no copiar esta línea
add_filter('the_content', 'dcms_related_content');
function dcms_related_content( $content ){
if ( ! is_single() ) return $content;
$post_id = get_the_ID();
// Verificamos si existe en cache
$posts = wp_cache_get('dcms-'.$post_id, 'group_related');
if ( ! $posts ) {
// Obtenemos los datos desde la BD
$posts = get_posts([
'category_name' => 'noticias',
'post__not_in' => [$post_id],
'numberposts' => 4
]);
// Grabamos en la cache los resultados
if ( $posts ) {
wp_cache_set('dcms-'.$post_id, $posts, 'group_related', DAY_IN_SECONDS);
}
}
// Imprimimos los resultados encontrados
$str = '';
if ( $posts ){
$str .= "<h3>Entradas Relacionadas</h3>";
$str .= "<ul>";
foreach ($posts as $post) {
$str .= sprintf('<li><a href="%s">%s</a></li>',
esc_url(get_permalink($post->ID)),
esc_html(get_the_title($post->ID)));
}
$str .= "</ul>";
}
return $content.$str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment