Add an attribute to the root from functions.php with add_filter

Question

I followed this link. First thing I did was to add my dark-mode switcher, add JS to handle it and edit my CSS accordingly. Thing is, I didn’t exactly do that, I used the possibility to have a global html attribute at the root and writing CSS like this:

:root {
  /* some colours */
}

[data-theme="dark"] {
  /* some colours when the attribute data-theme is set to dark */
}

So I needed to change a bit the tutorial I followed to, instead of change the class of body, change the attribute of the root (in my case, html). Instead of writing

$('body').addClass('dark-mode');

I write

$(document.documentElement).attr('data-theme', 'dark');

And it goes really well.

At the end of this link there is a php function to check if the cookie is present and set the body class immediately to avoid doing it from a JS function:

<?php
/**
 * Enable dark theme mode
 * Forked from https://wordpress.org/plugins/wp-night-mode/
 */
function yonkov_dark_mode($classes) {
    $yonkov_night_mode = isset($_COOKIE['yonkovNightMode']) ? $_COOKIE['yonkovNightMode'] : '';
    //if the cookie is stored..
    if ($yonkov_night_mode !== '') {
        // Add 'dark-mode' body class
        return array_merge($classes, array('dark-mode'));
    }
    return $classes;
}
add_filter('body_class', 'yonkov_dark_mode');

In my case I don’t want to change the body class, I want to change the html attribute but I can’t find the hook to do so, is there a solution to my problem?

0
, , Lhooq 3 years 2020-07-07T09:10:20-05:00 0 Answers 55 views 0

Leave an answer

Browse
Browse