1

Is there any way of getting a node by its post type? I've tried with the following code, but it doesn't really work.

$query = \Drupal::entityQuery('front_page_slider');

As far as I read on tutorials, it should work when the content type is front_page_slider. Instead, it returns an error.

The "front_page_slider" entity type does not exist.

5

What you call post type is for Drupal a content type, or an entity bundle. The first argument of \Drupal::entityQuery() is the entity type that, in the case of nodes, is node.

The code you need is the following one.

use \Drupal\node\Entity\Node;

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->execute();

$nodes = Node::loadMultiple($nids);

Note I added the condition('status', 1) line, which returns only the published nodes; if you are not interested only in the published nodes, you can leave that line off.

Furthermore, if you are executing the code without showing the result to the currently logged-in user, for example because it runs at cron time, you should disable the access check, and use the following code.

// Put the following line at the beginning of the file containing the code.
use \Drupal\node\Entity\Node;

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->accessCheck(FALSE)
  ->execute();

$nodes = Node::loadMultiple($nids);

Differently, you would get only the nodes for which the currently logged-in user has access.
In the example of a hook_cron() implementation, that user is the anonymous user. Without the accessCheck(FALSE) line, the code would get only the published nodes to which anonymous users have access, which could be none, if the user permissions don't allow anonymous users to see nodes.

accessCheck(FALSE) is used by node_access_rebuild(), which contains the following lines. (Read the comment before the code.)

  // Disable access checking since all nodes must be processed even if the
  // user does not have access. And unless the current user has the bypass
  // node access permission, no nodes are accessible since the grants have
  // just been deleted.
  $entity_query->accessCheck(FALSE);

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.