4

I try to find a way to get all nodes by a part of the url alias in the nodes. I know i get a specific node by the complete url alias. For example:

$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');
if(preg_match('/node\/(\d+)/', $path, $matches)) {
    $node = \Drupal\node\Entity\Node::load($matches[1]);
}

And I know I can find multiple nodes by entity query:

$nids = \Drupal::entityQuery('node')
            ->condition('type','page')
            ->condition('status',1)
            ->sort('created', 'DESC')
            ->range(0, 20)
            ->execute();

But I want to know how I can implement an additional condition to filter nodes by a part of the URL alias for example "/news/*". I need all nodes with this url fragment.

baikho
  • 5,203
  • 4
  • 40
  • 47
wiifree
  • 55
  • 1
  • 7
  • service name is `path_alias.manager`. so the first line of the code of your question should be: `$path = \Drupal::service('path_alias.manager')->getPathByAlias('/this-is-the-alias');` . thank you I have found the answer in your question – Reza Bayat Jun 21 '21 at 13:40

2 Answers2

1

Can try this- Reference https://www.jonkamke.com/blog/2019/5/load-a-node-via-url-alias

  <?php
    /** @var Drupal\Core\Url $url */
    $url = $variables['url'];
    if ($url instanceof Drupal\Core\Url) {
      $nid = $url->getRouteParameters()['node'];
      /** @var \Drupal\node\Entity\Node $node */
      $node = Node::load($nid);
      if ($node instanceof Node) {
        $type = $node->getType();
      }
    }
Sumit Kumar
  • 156
  • 4
0
$input = '/this-is-the-alias';
$node_query_result = [];
$path_query = \Drupal::database()->select('path_alias', 'a');
$path_query->addField('a', 'path');
$path_query->condition('a.alias', '%' . $input . '%', 'LIKE');
$path_query_result = str_replace('/node/', '', $path_query->execute()->fetchCol());
if ($path_query_result) {
  $node_query = \Drupal::database()->select('node_field_data', 'n');
  $node_query->addField('n', 'nid');
  $node_query->addField('n', 'type');
  $node_query->addField('n', 'title');
  $node_query->condition('n.status', NodeInterface::PUBLISHED);
  $node_query->condition('nid', $path_query_result, 'IN');
  $node_query_result = $node_query->execute()->fetchAll(\PDO::FETCH_ASSOC);
}
return $node_query_result;
Nik Ral
  • 92
  • 3