1

How can I use transient in this code for related post?

$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();
  • 2
    post__not_in is super expensive, orderby rand is even more expensive, you would be better manually skipping the current post in PHP with an if statement, and you'd be better randomly picking an orderby value in PHP rather than making MySQL do it ( stupendously slow, it has to create a copy of the posts table then re-order everything randomly, THEN it does the query, which btw will involve a costly table scan to avoid that 1 post you said in post__not_in ) – Tom J Nowell Apr 3 '18 at 23:59
1

If you set a transient it will go in wp_options table... that is probably not the best thing to do because you will be creating a transient for each post that way and that could mean a LOT of transients in your options table.

It makes more sense to store it as post meta and then expire it yourself with a simple check by recording your own data expiry time. eg:

$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();
  • +1 but probably best if possible just to remove the meta when relevant changes happen (in this case when a new post is saved into the category or a category is changed "out" of it. – Mark Kaplun Apr 4 '18 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.