Page 2 - Magento 2 Development
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 call CMS blocks in the XML layout, 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 create and enable a CMS block 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 flush
Although Magento 2 CMS blocks are managed directly from Magento admin using widgets and WYSWYG editor you can add them other ways too.
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,
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 optimizing Magento 2 reindex to getting current products 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);
As you know, order management in Magento 2 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 getting a current customer, 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;
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 order data by increment ID, 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
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 reindex Magento via CLI or even the admin panel, 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 Magento reindex 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 updating prices in bulk, to all of your products. This will cause 40K indexes to be invalidated.
Magento splits data for
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 get current product or current category.
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
While looking through various Magento 2 product types, 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.
Creating downloadable products 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);
Unlike the other Magento 2 product types, virtual products don't have a physical representation. These can be gift cards, services, certificates, warranties, etc.
Using the admin panel to create a virtual product 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
Having multiple product types 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 bundle product. 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 Magento 2 product types. 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 create grouped products 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);
While working with Magento 2 you perform a wide variety of tasks from installing extensions to configuring indexers and running static content deploy. 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 Magento 2 commands 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 |
Configurable products definitely stand out in the list of other Magento 2 product types. 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 simple products to the existing configurable products 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);
While product attribute is an individual characteristic of a product, product attribute set 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 how to create product attributes programmatically in Magento.
Use the following code to create an attribute set programmatically. Create the InstallData.php file in the app/code/Vendor/Module/Setup/InstallData.php.
<?php
namespace Vendor\Extension\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Setup\CategorySetupFactory;
Product attributes are characteristics of a product that help you offer customers a wide range of options and influence their purchasing decisions. Once you add product attributes in Magento, it doesn't end there. You can also use product attributes to define dynamic category rules, cart price rules, related product 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.
<?php
namespace 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
Related products are one of the most common ways to drive more sales in e-Commerce. You have to add related products manually or automatically through the related product rules 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.
<?php
namespace 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()
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 improve general security 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
Variable is a data item that can be applied multiple times and for different purposes. In Magento, variables are used to customize email templates. 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 |
As a store admin, you probably know how time-consuming it is to import products with their images to Magento 2 one by one especially if your store operates hundreds of items.
So, perhaps you are looking for easier ways to fulfill this task. Today, we'll cover how to import all products with images in Magento 2 using a local server and an external server.
Import Product Images in Magento from the Local Server
One of the possible ways to import product images in Magento is through the local server. For that:
1. Go to the Magento server and upload your image files to the default folder pub/media/import. You can select any other folder, just make sure to use the correct path while uploading product images to Magento.
2. In the CSV file add the name of each image file by SKU in the appropriate row and in the corresponding column depending on the image type (base_image, thumbnail_image, small_image, additional_image, etc.).
Note: if you want to add multiple images to one and the same SKU,
If you want to tailor your customer's experience to their needs you have to gather as much information about them as possible. Displaying unique pricing details or offering different shipping services based on customer groups required you to get current customer data in Magento.
Besides, customer age, gender and location are valuable marketing insights you can use to tweak your strategy.
Since you already know how to get current product and current category to customize them, in this guide you'll learn everything about getting logged in customers details.
Get Current Customer in Magento 2
You can get current customer in Magento via \Magento\Customer\Model\Session model using two methods.
Using Construct
<?php
namespace VendorName\ModuleName\Folder;
class Example
{
private $customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession
) {
$this->customerSession = $customerSession;
}
public function getCurrentCustomer()
{
return $this->customerSession->getCustomer();
Magento allows you to create and configure 6 different product types in the admin panel. Each product has a unique name, ID, and other details related to it. So, after you learn how to get current category, you have to know how to get current product in Magento 2.
Get Current Product in Magento 2
To get current product details you need to use Registry.
<?php
namespace VendorName\ModuleName\Folder;
class Example
{
private $registry;
public function __construct(
\Magento\Framework\Registry $registry
) {
$this->registry = $registry;
}
public function getCurrentProduct()
{
return $this->registry->registry('current_product');
}
}
?>
And now you can use getCurrentProduct() method:
// print current product data
if ($currentProduct = $example->getCurrentProduct()) {
echo $currentProduct->getName() . '<br />';
echo $currentProduct->getSku() . '<br />';
echo $currentProduct->getFinalPrice() . '<br />';
echo