Search code examples
prestashopprestashop-1.6

Prestashop 1.6 - How to add a dynamic class to the body element


In a Prestashop 1.6 site I need add a dynamic class to the body element (just in frontend).

The class should be 'group-[group-name-id]' where group-name-id is the group name id of the visitor.

Default Groups in Presashop are:

'1'--'Visitor'

'2'--'Guest'

'3'--'Costumer'

Is there a way to do this?

I found this, but it seems outdated, since it is for PS 1.4: https://www.prestashop.com/forums/topic/179593-adding-category-class-id-to-product-page-body/

enter image description here

UPDATE:

I almost get it thanks to @TheDrot answer (just below).

The only problem is this: [0]. I get this error: "Parse error: syntax error, unexpected '[', expecting ')' in /home/temporal-4/www/override/classes/controller/FrontController.php on line 36".

If I remove '[0]' it works but then in the class I get "group-array". I need to print all the values of the array like class="group-1 group-2 group-3".


Solution

  • You need to override FrontControllerCore class so create a file FrontController.php in folder 'override/classes/controller/' and put in this code

    class FrontController extends FrontControllerCore {
        public function init() 
        {
            parent::init();
            $this->context->smarty->assign('group_id', $this->context->customer->getGroups()[0]; // user can exist in multiple groups, so for this example im just grabbing first group id
        }
    }
    

    Then open header.tpl file in 'themes/your_theme/' and add code to body class

    group-{$group_id}
    

    If in body class you only see group-, be sure to delete class_index.php from cache folder and reload page.