Add a class to all page(groups)

  Previous article Next article  

Add a class to all page(groups)

  Article optimized for CMSMS 2.x

  Author:
  Last tested in: CMSMS 2.1.4
  Last updated: 29-06-2016
  Comments: 0

You can use this small tag to get yourself a class name for the current page. This is very useful when you want to apply particular CSS style only to a certain page, or a subset of pages.

User Defined Tag: page_class
/**
 * Add a class to all page(groups)
 *
 * http://www.cmscanbesimple.org/blog/add-class-to-page-groups
 **/


$classes = array();

$alias = \cms_utils::get_current_alias();
$pageid = \cms_utils::get_current_pageid();

$hm = cmsms()->GetHierarchyManager();
$node = $hm->find_by_tag('alias',$alias);

while ( $node && $node->get_tag('id') > 0 )  {
  array_unshift ( $classes, $node->get_tag('alias') );
  $node = $node->getParent();
}

echo implode($classes, ' ') . ' ';
if (count($classes) > 1)
  echo implode($classes, '-') . ' ';
echo 'page-' . $pageid;

  How to use

<body class="{page_class}">
Result

Let's say you are on the page with the following URL: /en/some/page

<body class="en some page en-some-page page-23">
In your stylesheet
/**
 * to affect "en" page and all it's children
 **/


body.en {
  /* style declarations */
}

/**
 * to affect only that specific page this is not 100% proof,
 * and might break in cases where you have similar URLs:
 * /en/some/page/ and /en/some-page/ will result in the same class name
 * for these cases you can use the ID of the page
 **/


body.en-some-page {
  /* style declarations */
}

body.page-23 {
  /* style declarations */
}


A2 Webhosting CMS Made Simple

  Comments

  Click here to leave a comment






This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)
  « Enter the CAPTCHA code (lower case)

Your IP address will be stored on submit. I reserve the right to change or delete your response without notice!
In case of abuse your IP address will be blocked!


Can I have your attention for a moment?

Did this tutorial help you solving a problem at your (clients) website and it saved you many hours of work? Great!!
Consider buying Rolf a cup of coffee in return! [ Click here ]


  0 Comments

No comments yet...

CMS Made Simple 2.2.2 - Tutorials, tips and tricks - CMSMS 2.2.2

Add a class to all page(groups)

  Article optimized for CMSMS 2.x

  Author:
  Last tested in: CMSMS 2.1.4
  Last updated: 29-06-2016
  Comments: 0

A2 Webhosting CMS Made Simple