Magento – How to use custom variables in Magento 2

admin-panelcustom-variablemagento-2.1.3

I have seen email templates to use built-in custom variables. Can someone explain how to use System -> Other Settings -> Custom Variables? For example category count, which will show in frontend.

Best Answer

From what I have used custom variable, it is only for passing admin manageable value to your code, you can access it as follows;

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->get('Magento\Variable\Model\Variable')->loadByCode('custom-variable-code');
$plain_value = $model->getPlainValue();

EDIT:

As asked by @Jonas de Herdt if you want to get store specific value for the variable you just need to pass the store code along with the custom variable code as follows;

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->get('Magento\Variable\Model\Variable')->loadByCode('custom-variable-code', 'store-code');
$plain_value = $model->getPlainValue();

Reminder that you should not use objectmanager directly in your code

Related Topic