How to create custom PrestaShop hook

PrestaShop hooks are great way to insert or add data at the most important places or actions of this great e-commerce platform. However, I am not satisfied with the quantity of default hooks and I sometimes use custom hooks with my custom modules. So how to implement custom hook and why not hard code all code without it?

Why hook is the right choice?

There is one big problem in my opinion with custom hooks because you need to hard code their position into the files that might be affected by CMS updates or etc. So it is just more easier to add one line of code than to copy and paste a bunch of code or even all page of it.

Secondly, hooks are easy used in modules which lets you save time and avoid headaches. You do not need to think about default page code as you just add addition to it, for example, you will not delete necessary code by accident.

Thirdly, it is just a good practice and manner of good and professional programmer.

How to create custom hook?

All active hooks are hold in Prestashop database table called ps_hook (ps_ is default database prefix and it will be on this article too), so you have to add it on module installation.

After you added hook information to the database, you must register it for later you which you do by calling this method:

Now you can easily insert your hook anywhere in the code.

However, it depends if you want it to execute raw PHP code or it will return a template file. There are two options and both are shown below.

With Smarty:

If you use the example with smarty, you must add {$MY_HOOK} variable where you want into your .tpl file that gets this assign. That’s about it.

Now you can add whatever you want to hooks function which you write like this:

Try it yourself.

, , ,

About Richard Smaizys

I am a freelance PHP developer working mostly on projects using PrestaShop for ecommerce (modules, theme integration, projects from 0 etc.) and WordPress as CMS solution.

11 Responses to “How to create custom PrestaShop hook”