如何在此代码中使用相关POST的瞬变?

时间:2018-04-03 作者:EntrepreneurVE

如何在这段代码中为相关帖子使用transient?

$related = get_posts(array(
    \'author\' => $author_id,
    \'category__in\' => wp_get_post_categories($post->ID),
    \'numberposts\' => 8,
    \'orderby\' => \'rand\',
    \'post__not_in\' => array(
        $post->ID
    )
));
if ($related)
    foreach ($related as $post) {
        setup_postdata($post);
        contenedor();
    }
wp_reset_postdata();

1 个回复
SO网友:majick

如果设置瞬态,它将进入wp_options 桌子这可能不是最好的做法,因为你将以这种方式为每个帖子创建一个过渡,这可能意味着你的选项表中有很多过渡。

将其存储为post-meta,然后通过记录自己的数据过期时间,通过简单的检查使其过期,这样做更有意义。例如:

$related = get_post_meta($post->ID, \'related_posts\');
if ($related) {
    $expires = get_post_meta($post->ID, \'related_expires\');
    if ($expires > time()) {
        $related = false;
        delete_post_meta($post->ID, \'related_posts\');
        delete_post_meta($post->ID, \'related_expires\');
    }
} 
if (!$related) {
    $related = get_posts(array(
        \'author\' => $author_id,
        \'category__in\' => wp_get_post_categories($post->ID),
        \'numberposts\' => 8,
        \'orderby\' => \'rand\',
        \'post__not_in\' => array(
            $post->ID
        )
    ));
    if ($related) {
         add_post_meta($post->ID, \'related_posts\', $related);
         add_post_meta($post->ID, \'related_expires\', time()+(24*60*60));
    }
}
if ($related) {
    foreach ($related as $post) {
        setup_postdata($post);
        contenedor();
    }
}
wp_reset_postdata();

结束