0

I am generating a report for the categories with duplicate Meta titles.

I have loaded all the categories and checking conditions one by one like below with the direct MySQL queries.

$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
$categoryId = 4;// current categoryID
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
$metaTitle = $category->getMetaTitle();
$query = "SELECT value FROM catalog_category_entity_varchar WHERE attribute_id='49' AND entity_id <> '".$categoryId."' and AND VALUE='".$metaTitle."'" ;
$Result = $connection->query($query);
$resultData = $Result->fetchAll();
if(count($resultData) > 0{
    $error = "Duplicate present";
}else{
    $error = "No Duplicate";
}

The above code working fine, but I like to modify the code by the standard. Is there any way to load category collection with filter and check the condition like above.

I am checking if the duplicate meta title presents apart from the selected category, needs to show the message.

Please, someone, suggest me how this can be achieved.

3

Add this below code in your file :

protected $_storeManager;
protected $catCollFactory;
public function __construct(
    ...
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $catCollFactory,
    ...
) {
    $this->_storeManager = $storeManager;
    $this->catCollFactory = $catCollFactory;
}


public function yourFunction(){
    $categoryFactory = $this->catCollFactory->create();
    $categories = $categoryFactory
        ->addAttributeToSelect('*')
        ->setStore($this->_storeManager->getStore());
    $catMetaTitleArr = [];
    foreach ($categories as $category) {
        if(in_array($category->getMetaTitle(), $catMetaTitleArr))
        {
            echo $category->getId(). "has duplicate meta title found";
        } else {
            $catMetaTitleArr[] = $category->getMetaTitle();
        }
    }
}

Remove generated and clean cache.

|improve this answer|||||
  • hello @Rohan. Thanks got it now. – Manjunath Feb 21 at 9:34

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.