Skip to content

How to replace an existing product’s url with a new product

I am duplicating a product, disabling the old one and want to set the url of the new product to replace the old product.

$duplicateParent = $this->productCopier->copy($oldproduct);  
$oldproduct->setUrlKey($existingUrlKey . '-old');
$oldproduct->setSku($existingSku . '-old');            
$oldproduct->setVisibility(1);

$duplicateParent->setUrlKey($existingUrlKey);

$oldproduct->save();
$duplicateParent->save();

It’s throwing an error because the URL exists already, even though I’ve changed the URL of the old product.

Is there a way to do this?