I created a drop-down attribute called "marketing" with 2 values : "sale" & "new" and I like to use a cron script that check every day :

  • if a product has a special price (or a catalog rule) => attribute "marketing" set to "sale"
  • if a product has no special price => attribute "marketing" empty
  • if a product is set to new from/to date => attribute "marketing" set to "new" or nothing

Idea is to filter in a catalog list all products that are "on sale" or "new". I know ho to check the conditions but not how to set the correct value for this attribute.

3 Answers 3


In your cron script, you can add the below code to fetch marketing dropdown attribute all options and values.

$this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$eavConfig = $this->_objectManager->create('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'marketing');
$options = $attribute->getSource()->getAllOptions(false);

$attributeValue = [];
foreach($options as $option) {
    $attributeValue[$option['label']] = $option['value'];    

then you can use directly value to set the data in product like below:


Hope this help !!


You can directly save attribute using below code

public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Eav\Model\Config $eavConfig,
\Magento\Catalog\Model\ResourceModel\Product\Action $action
    $this->_productCollectionFactory = $productCollectionFactory;
    $this->_eavConfig = $eavConfig;
    $this->productActionObject = $action;

public function execute() {
    $attribute = $this->_eavConfig->getAttribute('catalog_product', 'c_lager');

    $options = $attribute->getSource()->getAllOptions();

    foreach ($options as $key => $value) {
        if($key == 0)
        $options_final[$value['label']] = $value['value'];   

    //write your code to get data 'new' or 'sale' for $product

    //save attribute without triggering reindex
    $this->productActionObject->updateAttributes([$product->getId()], array('marketing' => $options_final['new']), 0);



The method $product->setData($attributeCode, $attributeValue) below could set custom attribute successfully.

$product = $this->productRepository->getById($productId); $product->setData($attributeCode, $attributeValue); $this->productRepository->save($product);


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.