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)
        ->range(0, 3)

    $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.
    – 4uk4
    Commented Feb 24, 2020 at 8:56

1 Answer 1


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).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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