1

I created a preprocess function in my recipe node page, inside that function I want to get 3 random recipes everytime the user accessess the page.

I have this code:

function sometheme_preprocess_node__recipe__full(&$variables)
{
    $nids = \Drupal::entityQuery('node')
        ->condition('type', 'recipe')
        ->condition('status', 1)
        ->addTag('sort_by_random')
        ->range(0, 3)
        ->execute();

    $variables['random_recipes'] =  \Drupal\node\Entity\Node::loadMultiple($nids);
}

But I notice that the recipes doesn't random because of Drupal cache system.

I don't want to turn off the overall cache system of Drupal for perfomance purposes.

I just want to disable cache programmatically when I get the random recipes.

  • A View with a random sort would be the easiest option, it disables caching automatically. BTW this doesn't work for anonymous traffic, here you need JS + AJAX. – 4k4 Feb 24 at 8:56
0

You'll need to make this an un-cachable block and place it on your template file, otherwise, you would have to turn off page caching.

But unless this is the only thing on that page, and there isn't something else in here worth caching, then you could alternately turn off caching for this specific page(s).

| improve this answer | |

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.