Wednesday, 5 June 2019

Product Collection with out of stock and In Stock in Magento 2

Product collection with out of stock and In stock.

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

$collection = $this->_productCollectionFactory->create();
        $collection->setFlag('has_stock_status_filter', true)
            ->addAttributeToSelect(array('*'))
            ->addFieldToFilter('visibility', 4)
            ->addCategoriesFilter(['eq' => $categories])
            ->addAttributeToSort('created_at', 'DESC')
            ->joinField('qty',
                'cataloginventory_stock_item',
                'qty',
                'product_id=entity_id',
                '{{table}}.stock_id=1',
                'left'
            )->joinTable('cataloginventory_stock_item', 'product_id=entity_id', array('stock_status' => 'is_in_stock'))
            ->addAttributeToSelect('stock_status')
            ->load();

Thursday, 23 May 2019

All Customer Groups in Admin system config multiselect

<?php

namespace Namespace\ModuleName\Model\System\Config\Source\Dropdown;

class Frontend implements \Magento\Framework\Option\ArrayInterface {

    protected $_groupCollectionFactory;
    public function __construct(\Magento\Customer\Model\ResourceModel\Group\CollectionFactory $groupCollectionFactory)
    {
        $this->_groupCollectionFactory = $groupCollectionFactory;
    }
   
    public function toOptionArray()
    {
        $this->_options = array();
        if (!$this->_options) {
            $this->_options = $this->_groupCollectionFactory->create()->loadData()->toOptionArray();
        }
        return $this->_options;
    }

}

Tuesday, 26 March 2019

Magento shipment view 404 error in admin side

In admin Side Sale->Shipments View 404 error

Solution is edit the below file at line num 49

Magento\Sales\Controller\Adminhtml\Shipment\AbstractShipment\View.php


$resultForward->setController('order_shipment')
                ->setModule('adminhtml')    // Change admin to adminhtml    

Thursday, 21 February 2019

Add Wyswing editor in Frontend in Magento2.3

Added the Following code in .phtml file

<textarea id="presonal_message"  name="presonal-message"></textarea>

<script>
    require([
    "jquery",
    "mage/translate",
    "mage/adminhtml/events",
    "mage/adminhtml/wysiwyg/tiny_mce/setup"
    ], function(jQuery){
        wysiwygcompany_description = new wysiwygSetup("presonal_message", {
            "width":"99%",  // defined width of editor
            "height":"200px", // height of editor
            "plugins":[{"name":"image"}], // for image
            "tinymce4":{"toolbar":"formatselect | bold italic underline | alignleft aligncenter alignright | bullist numlist | link table charmap","plugins":"advlist autolink lists link charmap media noneditable table contextmenu paste code help table",
            }
        });
        wysiwygcompany_description.setup("exact");
    });
</script>



Wednesday, 2 January 2019

Magento 2 Export order,customer and products tables only

Customer Tables Export

mysqldump -u username -p dbname customer_address_entity customer_address_entity_datetime customer_address_entity_decimal customer_address_entity_int customer_address_entity_text customer_address_entity_varchar customer_entity  customer_entity_datetime customer_entity_decimal customer_entity_int customer_entity_text customer_entity_varchar  customer_grid_flat customer_log customer_visitor persistent_session wishlist wishlist_item  wishlist_item_option > hkcustomers31dec.sql


Orders Tables Export


mysqldump -u username -p dbname gift_message quote quote_address quote_address_item quote_id_mask quote_item quote_item_option quote_payment  quote_shipping_rate reporting_orders sales_bestsellers_aggregated_daily sales_bestsellers_aggregated_monthly  sales_bestsellers_aggregated_yearly sales_creditmemo sales_creditmemo_comment sales_creditmemo_grid sales_creditmemo_item sales_invoice sales_invoiced_aggregated sales_invoiced_aggregated_order sales_invoice_comment sales_invoice_grid sales_invoice_item sales_order sales_order_address sales_order_aggregated_created sales_order_aggregated_updated sales_order_grid sales_order_item sales_order_payment sales_order_status_history sales_order_tax sales_order_tax_item sales_payment_transaction sales_refunded_aggregated sales_refunded_aggregated_order sales_shipment sales_shipment_comment sales_shipment_grid sales_shipment_item sales_shipment_track sales_shipping_aggregated sales_shipping_aggregated_order tax_order_aggregated_created  tax_order_aggregated_updated > hkorders31dec.sql

Product Tables List

cataloginventory_stock_item cataloginventory_stock_status cataloginventory_stock_status_idx cataloginventory_stock_status_tmp catalog_category_product catalog_category_product_index catalog_category_product_index_tmp catalog_compare_item catalog_product_bundle_option catalog_product_bundle_option_value catalog_product_bundle_price_index catalog_product_bundle_selection catalog_product_bundle_selection_price catalog_product_bundle_stock_index catalog_product_entity catalog_product_entity_datetime catalog_product_entity_decimal catalog_product_entity_gallery catalog_product_entity_int catalog_product_entity_media_gallery catalog_product_entity_media_gallery_value catalog_product_entity_media_gallery_value_to_entity catalog_product_entity_media_gallery_value_video catalog_product_entity_text catalog_product_entity_tier_price catalog_product_entity_varchar catalog_product_index_eav catalog_product_index_eav_decimal catalog_product_index_eav_decimal_idx catalog_product_index_eav_decimal_tmp catalog_product_index_eav_idx catalog_product_index_eav_tmp catalog_product_index_price catalog_product_index_price_bundle_idx catalog_product_index_price_bundle_opt_idx catalog_product_index_price_bundle_opt_tmp catalog_product_index_price_bundle_sel_idx catalog_product_index_price_bundle_sel_tmp catalog_product_index_price_bundle_tmp catalog_product_index_price_cfg_opt_agr_idx catalog_product_index_price_cfg_opt_agr_tmp catalog_product_index_price_cfg_opt_idx catalog_product_index_price_cfg_opt_tmp catalog_product_index_price_downlod_idx  catalog_product_index_price_downlod_tmp catalog_product_index_price_final_idx catalog_product_index_price_final_tmp catalog_product_index_price_idx catalog_product_index_price_opt_agr_idx catalog_product_index_price_opt_agr_tmp catalog_product_index_price_opt_idx catalog_product_index_price_opt_tmp catalog_product_index_price_tmp catalog_product_index_tier_price catalog_product_index_website catalog_product_link catalog_product_link_attribute_decimal catalog_product_link_attribute_int catalog_product_link_attribute_varchar catalog_product_option catalog_product_option_price catalog_product_option_title catalog_product_option_type_price catalog_product_option_type_title catalog_product_option_type_value catalog_product_relation catalog_product_super_attribute catalog_product_super_attribute_label catalog_product_super_link catalog_product_website catalog_url_rewrite_product_category downloadable_link downloadable_link_price downloadable_link_purchased downloadable_link_purchased_item downloadable_link_title downloadable_sample downloadable_sample_title product_alert_price product_alert_stock report_compared_product_index report_viewed_product_aggregated_daily report_viewed_product_aggregated_monthly report_viewed_product_aggregated_yearly report_viewed_product_index

Friday, 2 November 2018

How to remove empty attributes “No” in Magento 2?

 Override the to your theme
 app/code/{Packagename}/{themename}/Magento_Catalog/templates/product/view/attributes.phtml


Just keep line, <?php if($_data['value'] == 'N/A') continue;?> after <?php foreach ($_additional as $_data): ?> line,


 Full code,

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/**
 * Product additional attributes template
 *
 * @var $block \Magento\Catalog\Block\Product\View\Attributes
 */
?>
<?php
    $_helper = $this->helper('Magento\Catalog\Helper\Output');
    $_product = $block->getProduct();
?>
<?php if ($_additional = $block->getAdditionalData()): ?>
    <div class="additional-attributes-wrapper table-wrapper">
        <table class="data table additional-attributes" id="product-attribute-specs-table">
            <caption class="table-caption"><?= /* @escapeNotVerified */ __('More Information') ?></caption>
            <tbody>
            <?php foreach ($_additional as $_data): ?>
<?php if($_data['value'] == 'No') continue;?>
                <tr>
                    <th class="col label" scope="row"><?= $block->escapeHtml(__($_data['label'])) ?></th>
                    <td class="col data" data-th="<?= $block->escapeHtml(__($_data['label'])) ?>"><?= /* @escapeNotVerified */ $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif;?>

Thursday, 12 July 2018

Msgento Export the all Orders into CSV with Limited Headers

<?php
require_once('app/Mage.php');
    Mage::app();

    $data=Mage::getModel('sales/order')->getCollection();

$fp = fopen('exports_order.csv', 'w+');
//csve headers. You can give your own headers or extra headers
$csvHeader = array('order_id',
    'ship_name',
    'ship_address1',
    'ship_city',
    'ship_state',
    'ship_zip',
    'ship_country',
    'item_id',
    'qty',
    'ship_company',
    'phone_day',
    'email');
fputcsv( $fp, $csvHeader,",");
foreach($data as $row)
{
    //echo "<pre>";Mage::log($row->getData(),null,'orderdata.log');die('here');
    $_order=Mage::getModel('sales/order')->load($row->getId());
    $_shippingAddress = $_order->getShippingAddress();
    //echo "<pre>";Mage::log($_shippingAddress->getData(),null,'shipping.log');die('here');
    foreach ($row->getAllItems() as $item) {
    $product = Mage::getModel('catalog/product')->load($item->getProductId());
 
//echo "<pre>";Mage::log($item->getData(),null,'noworders.log');die();
fputcsv($fp, array($row->getId(),
    $_shippingAddress->getFirstname()." ".$_shippingAddress->getLastname(),
    $_shippingAddress->getStreetFull(),
    $_shippingAddress->getCity(),
    $_shippingAddress->getRegion(),
    $_shippingAddress->getPostcode(),
    $_shippingAddress->getCountry_id(),
    $item->getSku(),
    $item->getQtyOrdered(),
    $_shippingAddress->getCompany(),
    $_shippingAddress->getTelephone(),
    $_shippingAddress->getEmail()
    ) );

    }
 
}
fclose($fp);

Create Shipment for Order Using Script

<?php
$orderid = 1;
$order = Mage::getModel('sales/order')->load($orderid );
$shipmentItems = array();
foreach ($order->getAllItems() as $item) {
$shipmentItems [$item->getId()] = $item->getQtyToShip();
}

// Prepear shipment and save ....
if ($order->getId() && !empty($shipmentItems) && $order->canShip()) {
    $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($shipmentItems);
    $shipment->save();
}
$shipment_collection = Mage::getResourceModel('sales/order_shipment_collection');
$shipment_collection->addAttributeToFilter('order_id', $data[0]);
foreach($shipment_collection as $sc) {
    $shipment = Mage::getModel('sales/order_shipment');
    $shipment->load($sc->getId());
    if($shipment->getId() != '') {
$track = Mage::getModel('sales/order_shipment_track')
->setShipment($shipment)
->setData('title', $data[5])
->setData('number', $data[6])
->setData('order_id', $shipment->getData('order_id'))
->save();
    }
}
?>

Monday, 10 July 2017

Magento get All search terms using programatically

<?php
//echo "hiii";die("here");
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once(__DIR__ . '/app/Mage.php');
Mage::app();
umask(0);
$searchCollection=Mage::getModel('catalogsearch/query')->getCollection();
//echo "<pre>";print_r($searchCollection->getData());die("here");
$searchData = $searchCollection->getData();
foreach($searchData as $terms){
echo $terms['query_text'];
echo "<br />";
}
die("here");
?>

Friday, 7 July 2017

Magento2 Upgrade from 2.0.x-2.1.x

In composer.json change this line
"magento/product-community-edition": "2.0.0",
Also you should change the line 5 as well "version": "2.0.0", to keep it in sync.
to whatever version you want, and then run:
composer update
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
if any Authenication required give the public keys and private keys 
as a username and password of Your magento.com account login

Magento 9767 patch issue in checkout page customer registration

Saturday, 1 April 2017

Add Customer Address for existing customer using CSV

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$websiteId = $storeManager->getWebsite()->getWebsiteId();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
if(($handle = fopen("customers.csv", "r")) !== FALSE) {
while (( $csvFile = fgetcsv($handle, 1000, ",")) !== FALSE) {
//echo $csvFile[0];die;
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
$customer=$customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($csvFile[0]);
$data= $customer->getData();
//echo "<pre>";print_r($data);die('Ram');
$customer_id=$data['entity_id'];
try{
$addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');
$address = $addresss->create();
$address->setCustomerId($customer_id)
->setFirstname($csvFile[6])
->setLastname($csvFile[9])
->setCountryId($csvFile[17])
->setPostcode($csvFile[19])
->setCity($csvFile[15])
->setTelephone($csvFile[22])
->setFax($csvFile[18])
->setCompany($csvFile[16])
->setStreet($csvFile[21])
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
$address->save();
echo $customer_id . "Address is Added Successfully";
echo '<br/>';
}
catch(Exception $e){
echo $e->getMessage();
}
}
}
else{
echo $customer_id . "Address is not added Successfully";
}

Wednesday, 21 January 2015

Create the Custom Attribute to Customer

This Post is used for Create the custom drop down attribute to customer and these following files are placed in existing module.
Required files are:
1.Namespace/module/sql/install-1.1.10.php
2.Namespace/module/Model/Attribute/Source/warehouse.php

1.Namespace/module/sql/install-1.1.10.php

<?php
//$installer = new Mage_Customer_Model_Entity_Setup('core_setup');
$installer = $this;
$installer->startSetup();

$vCustomerEntityType = $installer->getEntityTypeId('customer');
$vCustAttributeSetId = $installer->getDefaultAttributeSetId($vCustomerEntityType);
$vCustAttributeGroupId = $installer->getDefaultAttributeGroupId($vCustomerEntityType, $vCustAttributeSetId);
$setup = Mage::getModel('customer/entity_setup', 'core_setup');
$installer->addAttribute('customer', 'warehouse_name', array(
        'label' => 'Warehouse Name',
        'input' => 'select',
        'type'  => 'varchar',
        'forms' => array('customer_account_edit','customer_account_create','adminhtml_customer','checkout_register'),
        'required' => 1,
        'user_defined' => 1,
        'source' => 'namespace_module/attribute_source_warehouse',
       // 'source' => NULL,
));

$installer->addAttributeToGroup($vCustomerEntityType, $vCustAttributeSetId, $vCustAttributeGroupId, 'warehouse_name', 0);

$oAttribute = Mage::getSingleton('eav/config')->getAttribute('customer', 'warehouse_name');
$oAttribute->setData('used_in_forms', array('customer_account_edit','customer_account_create','adminhtml_customer','checkout_register'));
$oAttribute->save();

$installer->endSetup();
?>

2.Namespace/module/Model/Attribute/Source/warehouse.php

<?php
class Namespace_module_Model_Attribute_Source_Warehouse extends Mage_Eav_Model_Entity_Attribute_Source_Abstract{
    protected $_options = null;

    public function getAllOptions($withEmpty = false){
        if (is_null($this->_options)){
            $this->_options = array();

            $this->_options[] = array('label'=> 'Option 1', value=>1);
            $this->_options[] = array('label'=> 'Option 2', value=>3);
            $this->_options[] = array('label'=> 'Option 3', value=>3);
        }
        $options = $this->_options;
        if ($withEmpty) {
            array_unshift($options, array('value'=>'', 'label'=>''));
        }
        return $options;
    }
    public function getOptionText($value)
    {
        $options = $this->getAllOptions(false);

        foreach ($options as $item) {
            if ($item['value'] == $value) {
                return $item['label'];
            }
        }
        return false;
    }
}
?>

Thursday, 8 January 2015

Magento2 Features and Changes

Component changes:
  • Removed Some payment Method and bundled Community Modules
  • Removed/Ceased: Mage_Oscommerce,Mage_XMlConnect,Mage_DataFlow,Mage_Compiler
Functional Changes:
  • Theme configuration: simple into one field
  • Enabling Profiler: handled by bootstrap
  • Customizing Email Template : no more relation to locale
  • Session Time out : Cookie lifetime(No more cookie life time)
File Structure Modularity:
In Magento 1.x
In Magento 2.x
app/deisgn/<area>/baase/default
app/code/<pool>/<module>/view/<area>
skin/<area>/base/default
same (no distinction)
js/
same
app/locale/en_Us/template/email/*.html
app/code/<pool>/<Module>/view/email/*.html
File structure:
Root ItemsWas in Magento 1.x
Root ItemsWas in Magento 2.x
errors
pub/errors
Includes
n/a
js
pub/js
media
pub/media
pkginfo
n/a
shell
dev/shell
skin
app/design/<appropriate theme>
index.php,cron.php,get.php
index.php,pub/index.php,pub/cron.php
bootstrap logic scartted across entry points
app/bootstrap.php
Frame Work Naming:
            Lot of Difference is there for Naming Conversion in Magento1.x and Magento2.x.
Magento2.x uses Real name and Fully Qualify module names across the board.

            Magento1.x:

·         Mage::getModel(‘catalog/product’);
·         getTableName(‘admin/role’)
·         customer, checkout

Magento2.x:
·         Mage:getModel(‘Mage_Catalog_Model_Product’) (real class name)
·         getTableName(‘admin_role’) (real table Name)
·         Mage_Customer,Mage_Checkout (Fully Qualify module names across the board

Frame Work Configuration:

·         Eliminated Excessive Section (up to 20% of all config.xml)
·         Move out some of the file to specialized files
·         simplified rewrites mechanism
·         Added merging mechanism that allows XMl-Schema validation (implemented for        new types of configuration)
               
Frame Work Significant Other:

1.      Controller : formally separated routing of application areas
2.      View: Unlimited theme fall back hierarchy
3.      Introduced container (Structural elements in layout in addition to blocks)
4.      Eliminating skins (only themes remain) eliminating packages physically from the file
5.      Managing themes and design packages in entities in database
6.      decoupling controllers from layout through universal “context” engine
7.      Migrating to Jquery
8.      Model service Layer
9.      Improving Performance for API routing and granular loading of WSDL for only requested resources

User Experience:

A.      Information Architecture of the menus
B.      Product creation flow
C.      Taxes UX
D.      Navigation ACL
E.   Backend usability and UI
Magento tools:
a.       Migration tools to assists data and code from 1.x to 2.x
b.      applications/ components /themes deployment (installation/ upgrade as new tools)

c.       Zend Framework 2

Wednesday, 7 January 2015

Magento2 Installation Steps

Step1: Download the Magento2 from https://github.com/magento/magento2  (or)
Step2: Download the composer.exe file from https://getcomposer.org/download/ and install it.
Step3: Copy the all composer files in magento2 root folder
Step4: Open the command prompt and go to magento2 folder and install the Composer Install
            Ex:c:\xampp\htdocs\magento2-master>composer install
If you got the any error like ‘php’ is not existing in external memory, we are create the Environment variables  in Advanced settings.
Step5:Run the magento2 in url like
             http://localhost/magento2-master/setup
Step6: Click on the Agree and Setup Magento Button
Step7: Click on Start Readiness Check button
Step8: Add the Database Details like
Database server hostname -- Mandatory
Database server username – Mandatory
Database server password – Not always Necessary
Database Name – Mandatory
Table Prefix – Optional
Step9: Select the Web configuration details
Step10: Customize your store Details like Time Zone, Currency, Language
Step11: Create the Admin Account Details with Username, Email, Password
Step12: Last step is Install the magento2 go to Homepage and Backend
               Homepage: http://localhost/magento2-master/

                Backend/admin: http://localhost/magento2-master/admin/

Magento Delete Products using CSV

<?php

require_once '../app/Mage.php';
Mage :: app("default") -> setCurrentStore( Mage_Core_Model_App :: ADMIN_STORE_ID );
$skuAll =array();
$file_handle = fopen("skus.csv", "r");
 while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);
$allSku = $line_of_text[0];

}
$products = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter(
        'sku', array('in' => $allSku)
    )
    ->load();

    if(is_array($products))
    {
        foreach ($products as $key => $pId)
        {
            try
            {
                $product = Mage::getModel('catalog/product')->load($pId)->delete();
                echo "successfully deleted product with ID: ". $pId ."<br />";
            }
            catch (Exception $e)
            {
                echo "Could not delete product with ID: ". $pId ."<br />";
            }
        }
    }
?>

Display The BestSelling Products In Magento

 Display The BestSelling Products In Magento


Step 1: Create a file app/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
    public function __construct(){
        parent::__construct();
        $storeId = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image'))
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->setOrder('ordered_qty', 'desc'); // most best sellers on top
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);
 
        $products->setPageSize(3)->setCurPage(1);
        $this->setProductCollection($products);
    }
}
Step2:Create a file app/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtml file and add the following lines of code in it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="page-title">
    <h2><?php echo $this->__('Best Seller Products') ?></h2>
</div>
<?php $_collectionSize = count($_products->getItems()) ?>
<table class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
    <?php if ($i%1!==0): ?>
    <tr>
    <?php endif ?>
        <td id="td_<?php echo $i;?>" <?php if($i%3==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
        <?php contentBlock('top') ?>
        <div id="cont_<?php echo $i;?>">
            <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>">
              <?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" 
             title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                <img src="<?php echo $this->helper('catalog/image')
                          ->init($_product, 'small_image')->resize(122, 109); ?>" width="122" height="109" 
                          alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" 
                          title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
            </a>
            <div class="a-center">                        
                <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>
                <?php echo $this->getPriceHtml($_product, true) ?>
                <?php if($_product->isSaleable()): ?>
                    <button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span>
                    <?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <div class="clear"></div>
                <?php else: ?>
                    <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
                    <div class="clear"></div>
                <?php endif; ?>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>">
                        <?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>">
                        <?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
                <?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
            </div>
        </div>
    </td>
    <?php if ($i%3==0 or $i==$_collectionSize): ?>
   </tr>
    <?php endif ?>
  <?php $i++; endforeach; $kol = $_collectionSize; ?>
</table>
<?php endif; ?>
Step 3: This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.
1
{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml"}}
Sweet, now we are able to show best selling products and most viewed products anywhere in our Magento store. If you run into any problem implementing the code, please feel free to comment and let me know. Subscribe our RSS To receive latest Magento development updates.

Product Collection with out of stock and In Stock in Magento 2

Product collection with out of stock and In stock. use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; $collection = $th...