PHP Magento Tips

Add CSS Class to Body After Customer Logged-in In Magento

Rate this posting:
{[['']]}

If you want to add a specific CSS-class to your HTML-body if a customer is logged in, e.g. if you want to make different styles for logged in and not logged in customers, there is a good way if you overwrite the HTML-Block of the Page module.

You can easily achieve by updating in layout.xml files but this is a good practice which will add class for all pages if customer is logged in.

Step 1: Create Module initialization file. Create file in app/etc/modules/Mycompany_Customerbodyclass.xml and add below code in it.

<?xml version="1.0" encoding="UTF-8"?>
<config>
  <modules>
    <Mycompany_Customerbodyclass>
      <active>true</active>
      <codePool>local</codePool>
    </Mycompany_Customerbodyclass>
  </modules>
</config>

Step 2: Create Module config file. Create file in app/code/local/Mycompany/Customerbodyclass/etc/config.xml and add below code in it.

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Mycompany_Customerbodyclass>
            <version>1.0.0</version>
        </Mycompany_Customerbodyclass>
    </modules>

    <global>
        <blocks>
            <page>
                <rewrite>
                    <html>Mycompany_Customerbodyclass_Block_Html</html>
                </rewrite>
            </page>           
        </blocks>
    </global>
</config>

Step 3: Create Block file. Create file in app/code/local/Mycompany/Customerbodyclass/Block/Html.php and add below code in it.

<?php

class Mycompany_Customerbodyclass_Block_Html extends Mage_Page_Block_Html
{
    public function __construct()
    {
        parent::__construct();
        
        /* @var Mage_Customer_Model_Session */
        $customer = Mage::getSingleton('customer/session');
        
        /**
         * Add logged in class to body if customer is logged in
        */
        if($customer->isLoggedIn()) {
            $this->addBodyClass('customer-logged-in');
        }
    }
}

Now Check your front end. When you login there is new "customer-logged-in" class will be added to the HTML body.
Tag : Magento
0 Comments On "Add CSS Class to Body After Customer Logged-in In Magento"

Back To Top