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 loves dabbling in other languages like Go and Ruby. Technical topics that interest me are monitoring, security and performance. I'm also a stickler for good documentation and clear technical writing.

During the day I lead a team of developers and solve challenging technical problems at Rightpoint where I mainly work with the Magento platform. I've also spoken at a number of events.

In my spare time I blog about tech, work on open source and participate in bug bounty programs.

If you'd like to get in contact, you can find me on Twitter and LinkedIn.