Magento 2 – Get Custom Variables

Under , , | Posted by admin | 0 Comments

You may have recently wondered how to get a specific custom variable in Magento 2.

The old way of doing this in Magento 1 looked similar to this.


In magento 2 we need to add the correct class to our constructor.

    protected $_variable;

    public function __construct(
        \Magento\Variable\Model\Variable $variable
    ) {
        $this->_variable = $variable;

Then in our custom function we can get the values of our custom variable like so.

$vendorExceptionList = $this->_variable->loadByCode('my_custom_variable')->getValue('plain');
$vendorExclusions = explode(', ', $vendorExceptionList);

You can also load a custom variable by its ID.


If this was helpful to you please feel free to comment below.