I would like to add dynamic classes from templates to tags like <main>, <header>, <footer> which are defined in header.php and footer.php. This is something I would like to acheive:


<!doctype html>
<html <?php language_attributes(); ?>>
    <meta charset="<?php bloginfo( 'charset' ); ?>" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="profile" href="https://gmpg.org/xfn/11" />
    <?php wp_head(); ?>

<body <?php body_class(); ?>>
    <header class="<?php dynamic_header_class(); ?>">
    <main class="<?php dynamic_main_class(); ?>">
        <div id="content" class="site-content">


Template Name: About Page
// Add header-interior class to <header>
// Add main-map-container class to <main>


Template Name: Contact Page
// Add header-exterior class to <header>
// Add main-no-footer class to <main>

Wordpress do have body_class() and post_class() but they are limited to <body> tag and corresponding <div> respectively. Coming from twig which has a very easy way to do these things using {% set %} tag. Can something reusable function or filter be created in wordpress where I could add different classes from different templates to tags like <main>, <header> etc.

  • Would you be able to provide some examples of which classes you would like to be output in your markup? With specific examples it makes suggestions a lot easier. For example: <header class="template-name post-id">. This may be useful: developer.wordpress.org/themes/references/… – Craig Pearson Apr 11 at 17:09
  • Alternatively, WP's body_class() provides a lot of default classes, and you can add custom classes to it. You could use inheritance i.e. body.page header to affect inner elements. – WebElaine Apr 11 at 17:40
  • yes, please post some code, what you want to achive. – user3135691 Apr 11 at 20:53
  • @craig I would like to have classes like <header class="modifier {$dynamicClass1}" > from template A, similarly <header class="modifier {$dynamicClass2}" > from Template B. This are all CSS predefined class that change the look of of header accordingly. Also I don't want to use those conditional class, because there are atleast 10 templates, and as I asked in the question I need to add class on multiple tags like header, main, footer etc. Adding conditions would make things messy plus I want a more permanent and easy way of doing it using some type of custom function or filter. – hashtagerrors Apr 12 at 5:07
  • @webelaine I'm migrating a big project to wordpress, a lot of changes had to be made in css for inheriting css through body class which would take alot of time. If it was a fresh project inheritance surely is a good idea. – hashtagerrors Apr 12 at 5:14

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.