How to remove the Add to Cart button from Catalog pages in Magento 2?
Question
How to remove the Add to Cart button from Catalog pages only?
La solution
In Magento 2 they've hardcoded them into the catalog product list template.
This can be found around line 80 of app/code/Magento/Catalog/view/frontend/templates/product/list.phtml
:
<?php if ($_product->isSaleable()): ?>
<?php $postParams = $block->getAddToCartPostParams($_product); ?>
<form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
<input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
<input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
<?php echo $block->getBlockHtml('formkey')?>
<button type="submit"
title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
class="action tocart primary">
<span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
</button>
</form>
A few options exist to suppress them:
- Create an
around
plugin for the block and change$_product->isSaleable()
to return false for the render of the template, and swap it back afterward - Replace this template in your custom theme's layout
- Hide with CSS
Honestly hiding via CSS isn't the worst option here:
.catalog-category-view .action.tocart { display: none; }
Autres conseils
You can always hide it via CSS but i will highly recommend to copy the app/code/Magento/Catalog/view/frontend/templates/product/list.phtml
into YourVendor/YourTheme/Magento_Catalog/view/frontend/templates/product/list.phtml
and remove all the form code fall in the if ($_product->isSaleable()):
condition.
app\code\Vendorename\Modulename\etc
di.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\Product">
<plugin name="hidecartbutton" type="Vendorename\Modulename\Plugin\Hidecartbutton" sortOrder="1"/>
</type>
</config>
app\code\Vendorename\Modulename\Plugin
Hidecartbutton.php
<?php
namespace Vendorename\Vendorename\Plugin;
use Magento\Catalog\Model\Product;
class Hidecartbutton
{
protected $request;
public function __construct(
\Magento\Framework\App\Request\Http $request
) {
$this->request = $request;
}
public function afterIsSaleable(Product $product, $isSaleable)
{
// get product data
$page_name = $this->request->getFullActionName();
$page_arr = [];
$page_arr[] = "catalog_product_view";
// $page_arr[] = "catalog_category_view";
if (in_array($page_name, $page_arr)) {
return false;
} else {
return $product->isSalable();
}
}
}