MENU

Add a class to all page(groups)

  Previous article Next article  

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)
 *
 * https://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 (isset($classes) && 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 */
}


Buy Me A Coffee


  Comment Form

ReviewManager

Click here to open the form

ReviewManager

  0 Comments

No comments yet...

Buy Me A Coffee

CMS Made Simple - Tutorials, Tips and Tricks - CMSMS

Add a class to all page(groups)

  Article optimized for CMSMS 2.x

  Author:
  Last tested in: CMSMS 2.2.19
  Last updated: 01-07-2018
  Comments: 0
  http://cms.ms/q5Q6


Buy Me A Coffee




Advertisement


Ads help me to help you! Thanks!

Ads help me to help you! Buy products from these advertisers!