function node_get_recent

Same name in other branches
  1. 7.x modules/node/node.module \node_get_recent()
  2. 8.9.x core/modules/node/node.module \node_get_recent()
  3. 10 core/modules/node/node.module \node_get_recent()

Finds the most recently changed nodes that are available to the current user.

Parameters

$number: (optional) The maximum number of nodes to find. Defaults to 10.

Return value

\Drupal\node\NodeInterface[] An array of node entities or an empty array if there are no recent nodes visible to the current user.

File

core/modules/node/node.module, line 691

Code

function node_get_recent($number = 10) {
    $account = \Drupal::currentUser();
    $query = \Drupal::entityQuery('node');
    if (!$account->hasPermission('bypass node access')) {
        // If the user is able to view their own unpublished nodes, allow them
        // to see these in addition to published nodes. Check that they actually
        // have some unpublished nodes to view before adding the condition.
        $access_query = \Drupal::entityQuery('node')->condition('uid', $account->id())
            ->condition('status', NodeInterface::NOT_PUBLISHED);
        if ($account->hasPermission('view own unpublished content') && ($own_unpublished = $access_query->execute())) {
            $query->orConditionGroup()
                ->condition('status', NodeInterface::PUBLISHED)
                ->condition('nid', $own_unpublished, 'IN');
        }
        else {
            // If not, restrict the query to published nodes.
            $query->condition('status', NodeInterface::PUBLISHED);
        }
    }
    $nids = $query->sort('changed', 'DESC')
        ->range(0, $number)
        ->addTag('node_access')
        ->execute();
    $nodes = Node::loadMultiple($nids);
    return $nodes ? $nodes : [];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.