Created
November 3, 2020 16:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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