How to update Magento community edition using CLI

composer require magento/product-community-edition 2.2.6 --no-update
composer update
rm -rf var/di var/generation var/cache var/view_preprocessed generated/*
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento indexer:reindex
php bin/magento deploy:mode:set production

if you receive any errors post installation, try this hard fix

rm -rf app/code/Magento/ var/* vendor/*
chmod 777 -R *
composer update && composer install
php -f bin/magento setup:static-content:deploy
find . -type d -exec chmod 775 {}
find . -type f -exec chmod 660 {}
chmod u+x bin/magento
bin/magento maintenance:disable
bin/magento cache:clean

How to shift category description below products in Magento 2

In your theme folder, add Folder Magento_Catalog/layout and in layout folder add file catalog_category_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
<move element="category.view.container" after="content" destination="main.content" />
    </body>
</page>

How to add custom attributes in Magento 2 product CSV export

Core Method is to edit the file
/vendor/magento/module-catalog-import-export/Model/Export/Product.php

and Edit the variable $_exportMainAttrCodes

Add your attributes in the array like “custom1″,”custom2”, etc and save the file.

Next time you export the csv, you will see new columns in the file.

Remove Compare feature from Magento 2

How to remove “Add to Compare” links in sidebar and product page in Magento 2 product pages

Magento 2 Community has a default feature of comparison lists for multiple products. Learn how you can disable the “Add to Compare” feature in magento2 community edition.

Add the following lines in default.xml of your theme folder

	<referenceBlock name="catalog.compare.sidebar" remove="true"/>
	<referenceBlock name="catalog.compare.link" remove="true"/>
	<referenceBlock name="related.product.addto.compare" remove="true"/>
	<referenceBlock name="view.addto.compare" remove="true"/>
	<referenceBlock name="upsell.product.addto.compare" remove="true"/>

CORS policy for subdomains – htaccess – apache server

Works for Magento 2.2x

Cross-Origin Resource Sharing header for Access-Control-Allow-Origin for Subdomains

SetEnvIf Origin "^(.*\.yourdomain\.com)$" OSD=$1
Header set Access-Control-Allow-Origin "%{OSD}e" env=OSD
Header set Access-Control-Allow-Methods: "*"
Header set Access-Control-Allow-Headers: "*"

or a general format for simple copy paste:

SetEnvIf Origin "^(.*)$" OSD=$1
Header set Access-Control-Allow-Origin "%{OSD}e" env=OSD
Header set Access-Control-Allow-Methods: "*"
Header set Access-Control-Allow-Headers: "*"

How to manage Magento 2 product attribute values options using console

This is an update to my previous script which was used to add custom product attribute values using backend –
Add values to product attribute

Read the previous^ part to get introduction about how it works. you will have to use browser console (ctrl + shift +j in Google chrome)

First of all initialize the array mimim with the final set of values you want to see in backend. The script then automatically removes the extra options first(values which are not in mimim but in present in backend), then it adds the remaining values from mimim (which are in mimim but not at backend)

$jq=new jQuery.noConflict();
var mimim=["Abalone",
"Titanium Druzy",
"Tourmaline",
"Turquoise",
"Yellow Zircon",
"Light Blue Druzy"];
var trans=[];var o=0;
$jq('#manage-options-panel tbody tr td:nth-child(3) input').each(
  function(a,b){
	//if(a>10)return false;
	//alert(b.value);
	trans.push(b.value);
	if($jq.inArray(b.value,mimim)==-1){ o++;$jq('#delete_button_'+b.name.slice(14,-4)).click(); trans.pop();}
});
alert(o+" items removed");
$jq.each(mimim,function(a,b){
//console.log($jq('#manage-options-panel tbody tr td:nth-child(3) input').val());
if($jq.inArray(b,trans)==-1){
$jq('#add_new_option_button').click();
$jq('#manage-options-panel tbody tr:last-child td:nth-child(3) input').val(b);
}

});

Insert Indian States in Magento Database

Connect to your server’s database using mysql cli or phpmyadmin and use the following query

INSERT INTO `directory_country_region` VALUES 
(NULL,"IN","AP","Andhra Pradesh"),
(NULL,"IN","AR","Arunachal Pradesh"),
(NULL,"IN","AS","Assam"),
(NULL,"IN","BR","Bihar"),
(NULL,"IN","CG","Chhattisgarh"),
(NULL,"IN","GA","Goa"),
(NULL,"IN","GJ","Gujarat"),
(NULL,"IN","HR","Haryana"),
(NULL,"IN","HP","Himachal Pradesh"),
(NULL,"IN","JK","Jammu and Kashmir"),
(NULL,"IN","JH","Jharkhand"),
(NULL,"IN","KA","Karnataka"),
(NULL,"IN","KL","Kerala"),
(NULL,"IN","MP","Madhya Pradesh"),
(NULL,"IN","MH","Maharashtra"),
(NULL,"IN","MN","Manipur"),
(NULL,"IN","ML","Meghalaya"),
(NULL,"IN","MZ","Mizoram"),
(NULL,"IN","NL","Nagaland"),
(NULL,"IN","OD","Odisha"),
(NULL,"IN","PB","Punjab"),
(NULL,"IN","RJ","Rajasthan"),
(NULL,"IN","SK","Sikkim"),
(NULL,"IN","TN","Tamil Nadu"),
(NULL,"IN","TL","Telangana"),
(NULL,"IN","TR","Tripura"),
(NULL,"IN","UK","Uttarakhand"),
(NULL,"IN","UP","Uttar Pradesh"),
(NULL,"IN","WB","West Bengal"),
(NULL,"IN","AN","Andaman and Nicobar Islands"),
(NULL,"IN","CH","Chandigarh"),
(NULL,"IN","DH","Dadra and Nagar Haveli"),
(NULL,"IN","DD","Daman and Diu"),
(NULL,"IN","DL","Delhi"),
(NULL,"IN","LD","Lakshadweep"),
(NULL,"IN","PY","Puducherry");

How to create Magento 2 category programmatically?

Use this code:

<?php
use \Magento\Framework\App\Bootstrap;
echo 'code by harshvardhanmalpani';
include('./app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
function createCategory($a='',$b=2,$c=true,$d='',$e='',$f='',$g='') {
global $objectManager;
$category = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create();
$category->setName($a);
$category->setParentId($b); // 1: root category.
$category->setIsActive($c);
$category->setCustomAttributes([
'description' => $d,
'meta_title' => $e,
'meta_keywords' => $f,
'meta_description' => $g,
]);
$objectManager->get('\Magento\Catalog\Api\CategoryRepositoryInterface')->save($category);
}
createCategory("Abc");
createCategory("Xyz",4,false,"description","m title");
?>

How to secure a folder by whitelisting one IP using HTACCESS and denying all others

The process involves matching all requests for an IP, if the IP does not match redirect all secured directory requests.

RewriteCond %{REMOTE_ADDR} !^120\.120\.120\.120
RewriteRule ^admin/.* - [L,R=403] 
RewriteCond %{REMOTE_ADDR} ^120\.120\.120\.120
RewriteRule ^admin$ - [L,R=403]

If you want to control this IP using a script, you can add 2 lines

###CUSTOM RULES###
# your rules will appear here using php script
###CUSTOM RULES###

Now add a script, say happy.php
and use the following code:

$htaccess = file_get_contents('.htaccess');
$ip= str_replace(".","\.",$_SERVER['REMOTE_ADDR']);
$rules="RewriteCond %{REMOTE_ADDR} !^".$ip."
RewriteRule ^admin/.* - [L,R=403]
RewriteCond %{REMOTE_ADDR} !^".$ip."
RewriteRule ^admin$ - [L,R=403]";
$problem="###CUSTOM RULES###\r\n".$rules.
"\r\n###CUSTOM RULES###";
#please copy the next line carefully, no extra spaces or new lines
$solution=preg_replace('/###CUSTOM RULES###.*?###CUSTOM RULES###/sm',$problem,$htaccess);
file_put_contents('.htaccess', $solution);

you can also specify your error page for specific http code: 403
ErrorDocument 403 /er.htm