Conditionally unpublish a nodes more than latest 20 I want to show the latest updated 20 nodes and unpublish rest of the nodes more than 20 for particular content types.

Here is my code I Have done for a single node

public function unpublishednode() {   
   $all_content_types = NodeType::loadMultiple();
    foreach ($all_content_types as $machine_name =&gt; $content_type) {
      if($machine_name == 'events') {
        $node = Node::load(389);  
        $node-&gt;setPublished(FALSE);
        $node-&gt;save(); 

      } 
    } 
}
You need an entity query to get the nodes filtered by the content type, sorted by the changed or created date and starting with the 21th node:

  $query = \Drupal::entityQuery('node');
  $nids = $query
    -&gt;condition('type', $type)
    -&gt;sort('changed', 'DESC')
    -&gt;range(20, PHP_INT_MAX)
    -&gt;execute();
  $nodes = Node::loadMultiple($nids);


You could also add a condition for published nodes, so that you don't load nodes that don't need to be unpublished:

    -&gt;condition('status', NodeInterface::PUBLISHED)