0

Is there an API to find the title of a page using only its alias ?

I managed to get the internal path with this code (although the multilingual part doesn't feel the easiest option):

/** * Function to resolve an alias and find the internal path, considering language prefixes. */ function get_internal_path_from_alias($alias) { $language_manager = \Drupal::service('language_manager'); // Check if the alias starts with a language code prefix (e.g., /fr, /en, /de). // Get all languages on the site. $languages = $language_manager->getLanguages(); $prefix_found = FALSE; // Loop through the languages to check if the alias contains a language prefix. foreach ($languages as $language) { $langcode = $language->getId(); if (strpos($alias, '/' . $langcode) === 0) { // We found a language prefix, so remove it from the alias. $alias = substr($alias, strlen('/' . $langcode)); $prefix_found = TRUE; break; } } // Get the alias manager service. $alias_manager = \Drupal::service('path_alias.manager'); // If no prefix is found, pass NULL for the language code (default). // If a prefix was found, pass the language code for the alias lookup. if ($prefix_found) { $path = $alias_manager->getPathByAlias($alias, $langcode); } else { $path = $alias_manager->getPathByAlias($alias); } // Return the resolved path (or NULL if not found). return $path; } 

But after that I'm not sure how to get the title of my internal path ? Also my function doesn't work with views.

What API could I use for this ?

1
  • 1
    This question is similar to: How can I get the node ID from a path alias?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 13, 2024 at 7:21

1 Answer 1

0

You can try this for nodes:

$path = \Drupal::service('path_alias.manager')->getPathByAlias('/your/path/alias'); $pathArray = explode("/", $path); $node = \Drupal\node\Entity\Node::load(end((array_values($pathArray)))); $nodeTitle = $node->getTitle(); 

Views of course, are a little trickier, but this is one approach that may work:

$routeProvider = \Drupal::service('router.route_provider'); $pathRoutePattern = $routeProvider->getRoutesByPattern('/your/path/alias'); $getAll = reset($pathRoutePattern->all()); $getDefaults = $getAll->getDefaults(); $viewId = $getDefaults['view_id']; $displayId = $getDefaults['display_id']; $view = \Drupal\views\Views::getView($viewId); $view->setDisplay($displayId); $viewTitle = $view->getTitle(); 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.