I have an url like this: http://drupal.dev/en/news-events

It's not my current page url. How can I get the page title by using above url ?


From below code example you can get the page title as your requirement

 $path = \Drupal::service('path.alias_manager')->getPathByAlias('/news-events');
 if(preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
 echo $node->getTitle();

Hope this helps. :)

  • There is an extra ")" in your last line code. I used your code in my custom block hook and get the error: Call to a member function getTitle() on null
    – Richard
    Jul 18 '17 at 7:37
  • removed extra ")"
    – parth.k
    Jul 18 '17 at 8:46
  • Yep. I removed extra ")" and still got same error.
    – Richard
    Jul 18 '17 at 8:49

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.