13

I'm attempting to perform a query to retrieve only the three most recent nodes of a certain content type.

$query = \Drupal::entityQuery('node')
    ->condition('type', 'blog_post')
    ->sort('field');
$nids = $query->execute();

I understand that I can use sort to specify the field I want the results to be sorted by. But how would I sort by the dates the nodes were published?

0

3 Answers 3

23
$query = \Drupal::entityQuery('node')
                ->condition('status', 1) 
                ->sort('created' , 'DESC'); 
9

'created' was the field. I was able to find this by looking at the fields being used in Core\Modules\node\src\Entity\Node.php

2
  • 4
    Note that created is not the date when the node was published, it is when the node was created. That can but most not be the same. Drupal by default doesn't store a publication date.
    – Berdir
    Commented Jun 24, 2016 at 15:51
  • However, this is the value shown and editable in the "Authored on" field.
    – Tim
    Commented Oct 24, 2017 at 11:48
1
\Drupal::entityQuery('node')
    ->condition('status', 1) 
    ->sort('changed' , 'DESC'); 

//Available fields
public function fields() {
  $fields = array(
    'nid' => $this
      ->t('Node ID'),
    'type' => $this
      ->t('Type'),
    'title' => $this
      ->t('Title'),
    'body' => $this
      ->t('Body'),
    'format' => $this
      ->t('Format'),
    'teaser' => $this
      ->t('Teaser'),
    'node_uid' => $this
      ->t('Node authored by (uid)'),
    'revision_uid' => $this
      ->t('Revision authored by (uid)'),
    'created' => $this
      ->t('Created timestamp'),
    'changed' => $this
      ->t('Modified timestamp'),
    'status' => $this
      ->t('Published'),
    'promote' => $this
      ->t('Promoted to front page'),
    'sticky' => $this
      ->t('Sticky at top of lists'),
    'revision' => $this
      ->t('Create new revision'),
    'language' => $this
      ->t('Language (fr, en, ...)'),
    'tnid' => $this
      ->t('The translation set id for this node'),
    'timestamp' => $this
      ->t('The timestamp the latest revision of this node was created.'),
  );
  return $fields;
}

Source

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.