Learn how to create URL Alias Programmatically in Drupal. Our Drupal Support team is here to help you with your questions and concerns.
Drupal create URL Alias Programmatically
Drupal is a well-known content management system. It offers developers several tools to customize and extend their websites. One such tool is the Path module. It lets us create custom URL aliases for content.
Today, we are going to take a look at how to programmatically create URL aliases in Drupal with Path module.
We can use the path_save() function, to generate URL aliases to improve the user experience.
How to Create URL Aliases Programmatically
Here is an example of how to make a URL alias:
use Drupal\Core\Url;
use Drupal\path_alias\Entity\PathAlias;
// Specify the internal path or route for which you want to create an alias.
$internalPath = 'node/123';
// Define the desired URL alias.
$alias = 'custom-url-alias';
// Create a URL object for the internal path.
$url = Url::fromInternalUri($internalPath);
// Set the desired alias for the URL.
$url->setOption('alias', '/' . $alias);
// Create a path alias entity.
$pathAlias = PathAlias::create([
'path' => $url->toString(),
'alias' => '/' . $alias,
]);
// Save the path alias.
$pathAlias→save();
In the above example, we have to replace node/123 with the internal path for which we want to create an alias. Similarly, replace ‘custom-url-alias’ with the URL alias.
The code uses the Url::fromInternalUri() method to generate a URL object for the internal path. Next, the setOption() method helps assign the alias to the URL.
After that, a PathAlias entity is created and then saved. Once the code is executed, the URL alias is created.
Our experts would like to point out that that we have to use statements at the beginning of our file to import the required classes.
Furthermore, this code has to be executed within a custom module or a custom script within the Drupal environment.
[Need assistance with a different issue? Our team is available 24/7.]
Conclusion
In brief, our Support Techs demonstrated how to create URL Alias Programmatically in Drupal.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
0 Comments