How to find if the target path in custom url rewrite exists in Magento 2

check if the target path for the custom URL is present in the URL rewrite table in Magento 2.

protected $_urlRewrite;

public function __construct(
    \Magento\UrlRewrite\Model\UrlRewrite $urlRewrite
) {
    $this->_urlRewrite = $urlRewrite;
}

    $UrlRewriteCollection=$this->_urlRewrite->getCollection()->addFieldToFilter('target_path', 'path_to_check')
    $deleteItem = $UrlRewriteCollection->getFirstItem(); 
    if ($UrlRewriteCollection->getFirstItem()->getId()) {
        // target path does exist
        $deleteItem->delete();
    }

Leave a comment

Your email address will not be published. Required fields are marked *