How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2? - Magento source24


Hello magento friends todays in this blog post im share with you to How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2.

To add URL rewrite programmatically for a product in Magento 2 using a root script, you can follow these steps:

➤ Create a root script:

Create a PHP file in the root directory of your Magento 2 installation. For example, name it add_product_url_rewrite.php.


➤ Include Magento's bootstrap and initialization:

Add the following code at the beginning of the add_product_url_rewrite.php file to load the Magento 2 bootstrap and initialize the application:


How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2? - Magento source24


➤ Replace PRODUCT_SKU, CATEGORY_ID, and NEW_URL_KEY with your desired values:

Modify the placeholders with the actual product SKU, the desired category ID where the product should appear, and the new URL key for the product.


➤ Create a function to add URL rewrite:


How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2? - Magento source24



➤ Call the function:

After defining the function, call it with the appropriate parameters:


How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2? - Magento source24


Replace PRODUCT_SKU, CATEGORY_ID, and NEW_URL_KEY with the actual values for the product you want to create the URL rewrite for.

Run the script:
Save the file and run it from the command line using PHP:

How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2? - Magento source24


Please note that this code assumes that you're using the default store ID (1). If you have multiple stores, you may need to adjust the storeId in the addProductUrlRewrite function accordingly. Additionally, ensure you have the appropriate product SKU, category ID, and URL key before running the script. Always make a backup of your database before running any script that modifies data.



Deepak Kumar Bind

Success is peace of mind, which is a direct result of self-satisfaction in knowing you made the effort to become the best of which you are capable.

Post a Comment

If you liked this post please do not forget to leave a comment. Thanks

Previous Post Next Post