It may well be that our online catalogue is not updated yet. We have a vast network of ingredients, our supply chain team will be happy to entertain any ingrendient enquiry.
Magento 2 is a flexible ECommerce platform that provides you with various options to customize your store to your needs. Thus, as a developer, you have to be aware of the coding matters to make everything works as flawlessly as possible.
There may be dozens of tasks that have to be solved programmatically, for instance, or . However, it always goes down to configuration. So, it might also be useful to know how to get config value in Magento 2. And this is exactly what you'll learn today.
There are two ways to get config value in Magento 2. Let's have a look at both in more detail.
Get Config Value Using Dependency Injection
One of the most common methods to get configuration value in Magento is dependency injection.
In order to apply it, you need to go to the phtml block file and create a _construct function:
<?php
namespace Vendor\ModuleName;
class ClassName
{
public $scopeConfig;
public function __construct( \Magento\Framework\App\Config\ScopeConfigInterface
Running a Magento 2 store may not be as easy as it seems. There are lots of things you have to take care of, such as sales, orders, clients, etc., to say nothing of the development part. You should know how to or , as well as be aware of some other commands.
It's impossible to keep in mind all the commands for every single situation when you just start. So, that's why we created a list of useful Magento 2 commands that will save time and lessen the possibility of any errors.
Want to know more about Magento commands? Keep reading, this article is just what you need.
SSH
Command
Description
php bin/magento list
Generates a list of commands
help
Shows help for a command
Cache
Command
Description
php bin/magento cache:clean
Cleanes the cache types
php bin/magento cache:enable
Enables the cache types
php bin/magento cache:disable
Disables the cache types
php bin/magento cache:flush
Flushes the cache types
php bin/magento cache:status
Displays the cache status
Setup
Command
While there is a multitude of Magento 2 themes available on the market, you might still want to create custom theme for your store. Why? Templates, layouts, graphics and styles offered in a theme don't always satisfy your business requirements. Besides, the default Magento 2 themes Luma and Blank won't suffice if you're .
So, to create custom Magento 2 theme that conveys your brand's "feel" you need to resort to custom development.
In this guide, we'll walk you through all steps you need to take to create a theme for Magento and cover the basics of how to override basic and theme layouts.
Ready to start?
In case you're looking for a ready-to-use speed-optimized Magento 2 theme, we already have one — Optimized Magento 2 Theme.
Before Custom Theme Development in Magento
The first important thing to remember before starting theme development in Magento is that you shouldn't change or edit the default Luma and Blank theme files. If you customize the default theme files, the update to the
Magento flexibility allows you to display CMS blocks in a multitude of ways. However, for those of you with technical knowledge, there are only two options.
You can either , or call them in the PHTML file. Today we'll focus of the second one.
Call CMS Block in PHTML File
To programmatically call the CMS block in .phtml template file use this code:
<?php echo $this->getLayout() ->createBlock(\Magento\Cms\Block\Block::class) ->setBlockId('my_cmsblock_identifier') //replace my_cmsblock_identifier with real CMS bock identifier ->toHtml();?>
Note: you need to for this method to work. If the CMS block is disabled or does not exist, this code will not display any content.
Using createBlock method is fast but not ideal in terms of best practices.
So what you can do is add a CMS block into your block using layout. Use the following code in a proper layout XML handle file and don't forget to once the layout is changed:
<referenceBlock name="my-main-phtml-block">
Although CMS blocks are managed directly from Magento admin using widgets there are other ways to .
If you have some technical skills you can just call CMS block in Magento using the XML file.
Call CMS Block Using XML File
Use the following code to add CMS blocks using Magento 2 layout XML:
<referenceContainer name="content">
<block class="Magento\Cms\Block\Block" name="unick_block_name">
<arguments>
<argument name="block_id" xsi:type="string">my_cmsblock_identifier</argument>
</arguments>
</block>
</referenceContainer>
You need to replace "my_cmsblock_identifier" with your CMS block Identifier or ID (we recommend using Identifier).
Display CMS Blocks Dynamically (by Date)
Even if you add CMS blocks programmatically using the XML file, they will still be static. It means that you'll need to replace the identifier or disable a block manually. But not if you use the .
This way, you can display your CMS blocks dynamically, by different dates, times and days of the week.
But that's
If you're a Magento developer, you certainly know that effective store management often requires programming work. There are lots of tasks you need to perform — from running static content deploy and to and media URLs. Some of these are rather time-consuming or even complicated at times.
However, it is much easier if you know the proper methods to use.
In this article, in particular, you'll learn how to get media URLs in Magento 2.
Get Media URL Using Dependency Injection
The dependency injection method is among the most common ones when it comes to getting media URLs in Magento.
So, to apply it, go to your phtml block file and create a _construct function:
public function __construct ( \Magento\Store\Model\StoreManagerInterface $storeManager ) { $this->_storeManager = $storeManager; }
After that you can get a media URL in your phtml file:
$mediaUrl = $this ->_storeManager-> getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
echo $mediaUrl;
Get Media URL
As you know, is quite a demanding process. It calls for full attention to the details and the ability to make quick decisions. Especially when it comes to customer-related information.
Just like , you should know how to get customer data by customer ID in Magento. And this is exactly what you'll learn today.
There are a few methods to use, so we'll look at each of them in detail.
Get Customer Data by Customer ID Using Factory Method
The factory method is among the most common ones. So, the code below will help you to get customer data by customer ID:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
$customerId = 1;
$customer = $customerFactory->load($customerId);
print_r($customer->getData());
echo $customer->getEmail() . PHP_EOL;echo $customer->getFirstname(). PHP_EOL; echo $customer->getLastname(). PHP_EOL;
Get Customer Data by Customer ID Using API
Even though Magento 2 is a very flexible and easy-to-manage eCommerce platform, operating an online store may be rather challenging sometimes. Same as , getting products by ID is certainly a crucial skill.
Since it is one of the most frequent operation ones comes across when working with Magento, you have to know how to do it. There are a few ways to do so, and in this article, you'll learn how to use each of them.
Get Product by ID Using Factory Method
The most common way to get a product by ID in Magento 2 is to use the factory method. To do that, use the following code:
protected $_productFactory;public function __construct( \Magento\Catalog\Model\ProductFactory $productFactory) { $this->_productFactory = $productFactory;}
After that, get the product by ID, by executing the below command.
$product = $this->_productFactory->create()->load($id);
Get Product by ID Using API Repository
API repository is the other method you can choose. Execute the following code to get product objects:
Since Magento architecture is structured in a way to store data in different database tables, all data have to be reindexed when you make any changes to your store. And while you can or even the , this process is still time-consuming.
In this guide, we want to help you optimize the process.
Since the Catalog Category Product indexer takes the longest to execute we'll take it as an example for this article. So, you can optimize execution time by changing with batch_size of the Catalog Category Product indexer.
However, to get a better picture of how this works, let's define what is a batch size and why you need to modify it.
How Magento Reindex Works?
Batch size is a number of indexes that will be processed at a time, one MySQL query.
Imagine that you have a store with 40k products, and you do some changes, like , to all of your products. This will cause 40K indexes to be invalidated.
Magento splits data for reindexing in the following way:
Number of batches = number of indexes
Providing high-quality service requires you to optimize multiple processes in your store, including order management. That being said, looking for certain order details might take some time, especially with hundreds of products.
Nevertheless, Magento allows you to eliminate the hard work. You can get order data by increment ID in Magento in multiple ways, the same as you can or .
So, in this article, you'll learn how to use each method.
Get Order Data by Increment ID Using Factory Method
The factory method is used the most frequently. Use the following code:
protected $orderFactory;
public function __construct(
\Magento\Sales\Model\OrderFactory $orderFactory
) {
$this->orderFactory = $orderFactory;
}
public function getOrderByIncrementId()
{
$orderIncrementId = 10000003;
$order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId);
}
Get Order Data by Increment ID Using API Repository
Here is one more option. You might as well use the API repository to get order by increment
While looking through various , you can't miss downloadable products. As the name suggests, these are digital products that can be downloaded — books, software, videos, etc. This type of content is becoming more and more popular these days. As a result, you can benefit greatly from having them in your store's catalogue.
via the admin panel may be rather challenging since it requires lots of steps. Fortunately, there is a programmatic way to optimize the process.
The following code will help you to create a downloadable product in Magento 2 programmatically:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('frontend');
try {
$product = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class);
$product
->setSku('sku')
Unlike the other , virtual products don't have a physical representation. These can be gift cards, services, certificates, warranties, etc.
Using the admin panel to is not the only way. You might as well be looking for some alternatives. In this case, you can try to create a virtual product programmatically and in this article, you'll learn how to do that.To create a virtual product in Magento 2 programmatically:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('frontend');
try {
$product = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class);
$product
->setSku('Main Virtual') // Set your sku here
->setName('Virtual Color Product') // Name of Product
->setAttributeSetId(4) // Attribute set id
->setStatus(1)
Having multiple listed in your store catalog helps to make the customer experience in your store more diverse. One of the many options you can provide is a . Basically, it consists of simple and virtual products that can be customized according to the client's preferences. Customers can choose the size, weight, color, etc. to get the very product they like.
Although, you can create bundle products from the admin panel creating bundle products programmatically is much faster. So in this article, you'll learn how to do that.
Use the below method to create a bundle product in Magento 2 programmatically.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(\Magento\Framework\App\State::class);
$state->setAreaCode('frontend');
try {
$bundleProduct = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class);
Grouped products are only one of many . What is special about them is that they consist of simple products that can be purchased separately or as a group. Moreover, grouped products don't have a price, since it's defined by its component products.
Of course, you can using the admin panel. However, you might also be looking for a programmatic way to perform this task.
If you want to know how to create grouped products programmatically, you've landed on the right page.
To create a grouped product in Magento programmatically use the following code:
<?php error_reporting(E_ALL);ini_set('display_errors', 1); use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get(\Magento\Framework\App\State::class);$state->setAreaCode('frontend'); try { $product = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class); $product->setTypeId(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE)
While working with Magento 2 you perform a wide variety of tasks from to configuring indexers and running . Magento CLI is a useful tool that not only enables you to run a variety of operations but simplifies Magento development in general.
However, you might get overwhelmed by running the same commands over and over again. That's exactly when Magento 2 command shortcuts come in handy.
Surprisingly, many developers don't know about this. So in this guide, we've gathered the and command shortcuts for your convenience.
SSH
Full command
Shortcut
php bin/magento list
php bin/magento l
Cache
Full command
Shortcut
php bin/magento cache:clean
php bin/magento c:c
php bin/magento cache:enable
php bin/magento c:e
php bin/magento cache:disable
php bin/magento c:d
php bin/magento cache:flush
php bin/magento c:f
php bin/magento cache:status
php bin/magento c:s
Setup
Full command
Shortcut
php bin/magento setup:backup
php bin/magento se:b
php bin/magento setup:config:set
php bin/magento se:c:se
Configurable products definitely stand out in the list of other . They come in handy when you want to provide your customers with multiple product options.
By default, Magento 2 doesn't allow you to assign the existing to the existing from the admin panel. The only option is to create a so-called placeholder in the configuration and then add the product you need instead of it.
That kind of solution is not really helpful, since it requires too many unnecessary steps. That is why a programmatic way to perform this task might of more use.
So, to add a simple product to a configurable product in Magento 2 programmatically, refer to the method below.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$simple_product = $objectManager->create(\Magento\Catalog\Model\Product::class);
$simple_product->setSku('test-simple');
$simple_product->setName('test name simple');
$simple_product->setAttributeSetId(10);
$simple_product->setSize_general(193); // value id of S size
While product attribute is an individual characteristic of a product, is a group of those characteristics that define a product. You will use product attributes every time when creating products in Magento.
If you need to create multiple product attributes, doing this via the admin panel might require a lot of time. So in case, you need to do it fast, create an attribute set in Magento 2 programmatically.
Note: before you create attribute sets you have to create product attributes. So you might need to have a look at our guide on .
Use the following code to create an attribute set programmatically. Create the InstallData.php file in the app/code/Vendor/Module/Setup/InstallData.php.
<?phpnamespace Vendor\Extension\Setup;
use Magento\Framework\Setup\InstallDataInterface;use Magento\Framework\Setup\ModuleContextInterface;use Magento\Framework\Setup\ModuleDataSetupInterface;use Magento\Catalog\Setup\CategorySetupFactory;use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
Product attributes are characteristics of a product that help you offer customers a wide range of options and influence their purchasing decisions. Once you , it doesn't end there. You can also use product attributes to define , cart price rules, , and multiple other options.
That being said, it is important for you to know how to create product attributes in Magento programmatically. Just in case you'll need to create multiple attributes faster.
To create product attributes in Magento programmatically create the InstallData.php file in the app/code/Vendor/Module/Setup/InstallData.php.
<?phpnamespace Vendor\Module\Setup;
use Magento\Eav\Setup\EavSetupFactory;use Magento\Framework\Setup\InstallDataInterface;use Magento\Framework\Setup\ModuleContextInterface;use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface{ private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory) { $this->eavSetupFactory
Related products are one of the most common ways to drive more sales in e-Commerce. You have to manually or automatically through the to increase the average order value. But there is one more way. You can get related products collection in Magento programmatically.
So if you want to avoid monotonous manual configuration of related products in Magento, keep reading.
To get related product collection in Magento 2:
1. Create an Extension.php file at app/code/Vendor/Extension/Block folder.
<?phpnamespace Vendor\Extension\Block;
use Magento\Framework\View\Element\Template;use Magento\Backend\Block\Template\Context;use Magento\Framework\Registry;
class Extension extends Template{ protected $registry; public function __construct( Context $context, Registry $registry, array $data = [] ) { $this->registry = $registry; parent::__construct($context, $data); } public function _prepareLayout() { return parent::_prepareLayout(); } public function getCurrentProduct() { return $this->registry->registry('current_product');}
If you treat your website security as a top priority, then you'll be able to run your business seamlessly and provide a flawless customer experience. As a store owner, you know that there are lots of files and clients' data that have to be kept safe.
Fortunately, Magento 2 provides you with a lot of features to and avoid any kinds of violations. But, unfortunately, those are not always enough. And that's when you need the security.txt to streamline vulnerability reporting.
If you don't know what security.txt is, don't worry. We've got you covered.
In this article, we'll explain everything you need to know about security.txt and how you can configure it in Magento.
What is Security.txt?
Security.txt is a security tool that allows gathering data about security contacts and policies of your website in one file. It is used by researchers who need to contact you to report security vulnerabilities.
Security.txt gives quick access to important files and contacts of people responsible
Variable is a data item that can be applied multiple times and for different purposes. In Magento, variables are used to . There are two types of variables: predefined and custom. Magento 2 gives you a great load of predefined (default) email template variables that will help you to adjust your email templates for personal usage.
Obviously, it is impossible to keep all of them in mind. So here you can find a complete list of Magento 2 email templates variables.
Additionally, you'll learn how to add your custom variable to email templates and use it in your emails.
Default Email Template Variables in Magento 2
Default Variable Description
Magento 2 Default Variable Used in Email Templates
Base URL
{|{config path="web/unsecure/base_url"}}
Secure Base URL
{|{config path="web/secure/base_url"}}
General Sender Name
{|{config path="trans_email/ident_general/name"}}
General Sender Email
{|{config path="trans_email/ident_general/email"}}
Sales Representative Sender Name
{|{config path="trans_email/ident_sales/name"}}