What is the best way, to add custom PHP code to my Shopware 6 Shop and how to do this? I need the code executed in all pages (so maybe simply add to the footer or header).
Sample code:
<?php
for ($i=1; $i<=10; $i++) {
echo 'hello world ' . $i . '<br>';
}
?>
I need it, adding some php scripts to the frontend / theme.
I have tried to create a plugin, but I did not find out, if it is possible and where to integrate my PHP code to execute in the footer or other pages.
Update:
Solution from @Feanor works perfect! It solved all my problems. Simple way to reproduce this, use console with:
bin/console plugin:create YourPluginName
Only yes to "Subscriber Event". Plugin refresh, install and activate. Then just add
use Shopware\Storefront\Event\StorefrontRenderEvent;
to the MySubscriber.php and replace the other code with the code from Feanor
Create "YourPluginName/src/Resources/views/storefront/layout/footer/footer.html.twig", add the rest of the code and have fun =)
Ok, there will be such solution. First, you should override current footer template. You neeed to create file in your plugin path views/storefront/layout/footer/footer.html.twig. My example is looking so
{% sw_extends '@Storefront/storefront/layout/footer/footer.html.twig' %}
{% block layout_footer_inner_container %}
{{ parent() }}
<div class="custom">{{customFooter|raw}}</div>
{% endblock %}
Second, you need to create a subscriber to the event Shopware\Storefront\Event\StorefrontRenderEvent I implemented it such way and it works
/**
* @return string[]
*/
public static function getSubscribedEvents()
{
return [StorefrontRenderEvent::class=>'onFooterLoad'];
}
/**
* @param StorefrontRenderEvent $event
* @return void
*/
public function onFooterLoad($event){
$result = '';
for ($i=1; $i<=10; $i++) {
$result.='hello world ' . $i . '<br>';
}
$event->setParameter('customFooter',$result);
}
Then this code will be executed on every frontend page. I don't provide services.xml and I think, you know, how to configure it and to implement subscriber class. Good luck with implementing it.