Press "Enter" to skip to content

Posts tagged as “plugin”

Adding Dark Mode to WordPress

Supporting dark mode now becomes an industry standard, I also received several requests from my viewers/readers recently thus I decided to add this feature. First thing in my mind is a plugin, I found WP Dark Mode, it’s feature rich and kind of worked until someone told me it didn’t work with cached pages. Then I found Darkmode.js, there’re several plugin versions but I decided to use the plain js version. It’s simple but makes the job done. There are only a few options you can play with, like the position, size, color and emoji of the icon, that’s it. Here’s mine.

Put the following code in header.php

Basically, it adds an overlay layer that applies a revert color filter (white -> black, blue -> yellow, etc) to ALL the content including images and iframes as well as syntax-highlighted code which I decided to ignore later on.

To ignore a few types of content, add the following code to header.php

The next thing is to apply a different color theme for code under darkmode. I plan to use classic for day-mode and sublime-text for darkmode. Although the author says the persistent darkmode setting is in cookies, but turns out it’s in localstorage. There are two scenarios we need to handle. 1) page loads with darkmode on, 2) user click button to toggle darkmode. We need to change the class for code blocks accordingly.

Put the following code in the footer.php, since we need to let the syntax-highlighter do the work first.

Or don’t forget to preload the darkmode theme since only the default theme will be loaded to reduce requests and bandwidth.

Put the following code in the header.php <head> section, replace with your domain and plugin version.

Finally it looks like below, not perfect but pretty good and easy to config. I hope wordpress could officially add dark mode in the future release such that all the themes and plugins could implement that (more work though).