Render a Category page via a Standalone script in Magento 2

Published: February 5, 2020

Tags:

In this post I’ll share a standalone script that can be used to render a Magento 2 category page programmatically. This script can come in handy when debugging production issues on category pages (e.g. unexpected product set). For example, it can be executed under strace to review files opened, queries sent, and their corresponding results.

The Script

The script is as follows. Change $categoryId and $storeId as needed.

<?php

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;

$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$configLoader = $obj->get('Magento\Framework\ObjectManager\ConfigLoaderInterface');
$obj->configure($configLoader->load('frontend'));

$response = $obj->get('Magento\Framework\App\Response\Http');

$categoryId = '3';
$storeId = '1';

$obj->get('Magento\Store\Model\StoreManagerInterface')->setCurrentStore($storeId);

$controller = $obj->get('Magento\Catalog\Controller\Category\View');

$request = $obj->get('Magento\Framework\App\RequestInterface');

$request->setRouteName('catalog');
$request->setControllerName('category');
$request->setActionName('view');

$request->setParams([
    'id' => $categoryId
]);

$request->setDispatched(true);

$page = $controller->dispatch($request);

$page->renderResult($response);

echo $response->getContent();

Max Chadwick Hi, I'm Max!

I'm a software developer who mainly works in PHP, but also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.

During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.

If you'd like to get in touch with me the best way is on Twitter.