Question

How to get the all custom category on homepage with products.

I want to create these types, Please check screens-short:- https://prnt.sc/r5b2q5

Showing this category:-

enter image description here

Above category showing this position:-

enter image description here

I want to custom getting all categories above the top seller products. and I want to the category showing homepage enable/disable attributes

category attributes are yes so category showing on the homepage with products.

Please help me

Thanks.

Was it helpful?

Solution

Create following files for that.
Step 1: registration.php and etc/module.xml

Step 2:Solwin\Module2\Setup\InstallData.php
<?php
namespace Solwin\Module2\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

    protected $eavSetupFactory;

    public function __construct(\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY,
            'is_enable_attribute11',
                [
                    'type'     => 'int',
                    'label'    => 'Display Category in List',
                    'input'    => 'Boolean',
                    'source'   => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                    'visible'  => true,
                    'required' => false,
                    'global'   => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                    'group' => 'General Information',

                ]
        );
        $setup->endSetup();
    }
}

Step 3: Solwin/Module2/view/adminhtml/ui_component/category_form.xml
<?xml version="1.0" encoding="UTF-8"?>

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="general">
        <field name="is_enable_attribute11">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">boolean</item>
                    <item name="formElement" xsi:type="string">checkbox</item>
                    <item name="label" xsi:type="string" translate="true">Display Category in List</item>
                    <item name="prefer" xsi:type="string">toggle</item>
                        <item name="valueMap" xsi:type="array">
                            <item name="true" xsi:type="string">1</item>
                            <item name="false" xsi:type="string">0</item>
                        </item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

Step 4:Solwin\Module2\Block\Categorylist.php
<?php

namespace Solwin\Module2\Block;

use Magento\Catalog\Model\Product;

class Categorylist extends \Magento\Framework\View\Element\Template
{
    protected $_categoryFactory;

    protected $_storeManager;

    protected $_categoryNameFactory;

    protected $_productCollectionFactory;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\CategoryFactory $categoryNameFactory,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collecionFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {
        $this->_coreRegistry = $registry;
        $this->_categoryNameFactory = $categoryNameFactory;
        $this->_categoryFactory = $collecionFactory;
        $this->_storeManager = $storeManager;
        parent::__construct($context, $data);
    }

    public function getEnableCategory()
    {
        $category = $this->_categoryFactory->create()
        ->addAttributeToFilter('is_enable_attribute11',1)
        ->setStore($this->_storeManager->getStore());
        return $category;
    }

    public function getCategoryName($categoryId)
    {
        $category = $this->_categoryNameFactory->create()->load($categoryId)->setStore($this->_storeManager->getStore());
        return $category;
    }

    public function getProductCollection($categoryId)
    {
      $category = $this->_categoryNameFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*');
       return $category;
    }
}


Step 5:Solwin/Module2/view/frontend/layout/cms_index_index.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
          <block class="Solwin\Module2\Block\Categorylist" template="Solwin_Module2::category.phtml"/>
        </referenceContainer>
    </body>
</page>

Step 6:Solwin/Module2/view/frontend/templates/category.phtml

<?php
$category = $block->getEnableCategory();

$imageBlock = $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct');
?>
<h1 align="center">Category  list</h1>
<div class="tab">
  <?php foreach($category as $categorydata) : ?>
    <?php
      $categoryid = $categorydata->getEntityId();
      $categoryFactory = $block->getCategoryName($categoryid);
      $categoryNameshow = $categoryFactory->getName();
      $categoryUrlShow = $categoryFactory->getUrl();
    ?>
      <button class="tablinks" onclick="openCity(event,'<?php echo $categoryNameshow; ?>')"><?php echo $categoryNameshow; ?></button>
  <?php endforeach; ?>
</div>
<?php foreach($category as $categorydata) {
  $categoryFactory = $block->getCategoryName($categorydata->getEntityId());
  $categoryNameshow = $categoryFactory->getName();
  ?>
  <div id="<?php echo $categoryNameshow; ?>" class="tabcontent">
    <ul class="category-products">
      <?php
      $prodcollection = $block->getProductCollection($categorydata->getEntityId());
      foreach($prodcollection as $product) {
        $productImage = $imageBlock->getImage($product, 'category_page_list');
          ?>
          <li class="productli">
              <a href="<?php echo $product->getProductUrl(); ?>">
                  <?php echo $product->getName();?>
                  <?php echo $productImage->toHtml();  ?>
              </a>
          </li>
          <?php
      } ?>
    </ul>
  </div>
  <?php
}
?>
<script>

var mybtn = document.getElementsByClassName("tablinks")[0];
mybtn.click();

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
</script>
<style>
/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}
.productli {
  width: 25%;
  margin: 0 auto;
  display: inline-block;
  border: 1px solid#ddd;
  padding: 10px;
  text-align: center;
}
</style>

OTHER TIPS

Magento provides the widget feature and you can use that to show category products on specified area. for reference see attached imagesenter image description here

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top