How to create a dynamic variable
Occasionally a feed needs logic that conditions and filters cannot express - a lookup against another table, a calculation with real branching, a format only you know the rules for.
A dynamic variable is the escape hatch: a small PHP script on your server that you can call from any feed template like a normal attribute. When the built-in tools run out, this is what is left, and it can do anything PHP can.
Create a new dynamic variable
1. Create a new variable in Magento
- Navigate to Catalog -> Advanced Product Feeds -> Dynamic variables.
- Click Add New Variable and fill in the following fields:
- Set the name of the variable.
- Set the unique identifier for the variable (used in feed templates).
2. Add PHP code for the variable
-
Log in to your Magento server.
-
Navigate to one of the following directories:
var/mst_feed/app/code/Mirasvit/Feed/(recommended for Magento Cloud)
-
Create a new PHP file with the exact name as the variable code.
ExampleIf the Variable Code is
gtin_variable, createvar/mst_feed/gtin_variable.php. -
Write your PHP code inside the file.
Use echo instead of return to output the value.
3. Validate and Use the Variable*
- Save the variable and reload the Magento admin page.
- The code section will display the PHP script fetched from the server.
- To test the variable, enter product IDs in the preview field.
- Use the variable in templates with:
{{ product.variable:your_variable_code }}
Example of dynamic variables
Get correct GTIN
Name: GTIN
Code: gtin
PHP code:
<?php
$gtin = $product->getGtin();
if (!$gtin) {
$gtin = $product->getId();
$gtin .= str_repeat('0', 12 - strlen($gtin));
}
echo $gtin;
?>
Usage in feed template:
{{ product.variable:gtin }}
Output:
124200000000
Add 20% to the final price
Name: Add percentage
Code: percentage
PHP code:
<?php
$price = $product->getFinalPrice();
echo number_format($price * 1.2, 2);
?>
Usage in feed template:
{{ product.variable:percentage }}
Get total stock quantity across all sources
Name: Summary stocks qty
Code: sum_stocks_qty
PHP code:
<?php
$sourcesData = $objectManager->get('\Magento\InventoryCatalogAdminUi\Model\GetSourceItemsDataBySku')
->execute($product->getSku());
$sumQty = 0;
foreach ($sourcesData as $sourceData) {
$sumQty += $sourceData['quantity'];
}
echo $sumQty;
Usage in feed template:
{{ product.variable:sum_stocks_qty }}
Display special price only if it's lower than regular price
Name: Custom special price
Code: custom_spec_price
PHP Code:
<?php
$finalPrice = $product->getFinalPrice();
$regularPrice = $product->getPrice();
if ($finalPrice < $regularPrice) {
echo number_format($finalPrice, 2);
} else {
echo '';
}
?>
Usage in feed template:
{{ product.variable:custom_spec_price }}