0

I have successfully managed to add the alias to the body class by creating a plugin. It uses vanilla JS and isn't overly problematic except when I combine and compress my JS it stops working. I'm not sure why. But I have always thought it better to achieve this via PHP anyway.

I came up with the below code using onBeforeCompileHead instead of onBeforeRender as I was trying to work out why it wouldn't work and I assume after the head had been compiiled that would be too late. Can anyone assist me in understanding why this code doesn't work?

<?php
/*------------------------------------------------------------------------
# Alias as body class
# ------------------------------------------------------------------------
# version 1.0.0
# author Kind of Useful
# copyright Copyright (C) 2019 Kind of Useful. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: https://www.kindofuseful.com
# Technical Support: info@kindofuseful.com
-------------------------------------------------------------------------*/

// Check to ensure this file is included in Joomla!
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

class plgSystemKouAliasAsBodyClass extends JPlugin
{   
    function onBeforeCompileHead()
    {

        $app            = JFactory::getApplication();

        // If we are on admin don't process.
        if (!$app->isClient('site'))
        {
            return;
        }

        $document       = JFactory::getDocument();
        $menu           = $app->getMenu();
        $active         = $menu->getActive();
        $alias          = ucfirst($active->alias);

        $prefix         = $this->params['prefix'];      

        if ($this->params['class'])                           // getParams and setParams only if something to add
        {
            $pageClass = $app->getParams()['pageclass_sfx'];

            $alias = $prefix . $alias;

            if (!empty($pageClass))                           // isset and not an empty string
            {
                $pageClass .= ' ' . $alias;   // append new class
            }
            else
            {
                $pageClass = $alias;          // declare new class
            }
            $app->setParams($pageClass);
        }       

    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.