2

I am creating a product programmatically, trying to set the visibility with below code

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

$product = $objectManager->create('\Magento\Catalog\Model\Product');

$product->setVisibility(4);

$product->save();

The above code works perfectly, but it is not working when I use like below.

$product->setVisibility('Catalog, Search');

The product is saving, but visibility is not set when used like above. Can anyone suggest me how to update the visibility? I am reading it from the csv file and updating.

3
$product->setVisibility('Catalog, Search');

This will not work because In Visibility you can set Integer value.

so work around is

$array =  [ 1 => 'Not Visible Individually',
            2 => 'Catalog',
            3 => 'Search',
            4 => 'Catalog, Search'
        ];

$currentValue = array_search("Catalog, Search",$array);
$product->setVisibility($currentValue);
2

We have to pass the Integer value for the "Catalog, Search" and it's 4.

When you check in Magento 2 admin. Visibility field have following options:

<option data-title="Not Visible Individually" value="1">Not Visible Individually</option>
<option data-title="Catalog" value="2">Catalog</option>
<option data-title="Search" value="3">Search</option>
<option data-title="Catalog, Search" value="4">Catalog, Search</option>

So you have to use code like

$visibility_array =  ['Not Visible Individually' => 1,
        'Catalog' => 2,
        'Search' => 3,
        'Catalog, Search' => 4
    ];

$visibility = $visibility_array['Catalog, Search'];
$product->setVisibility($visibility);

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.