Here’s how you can add a day and night mode for your wordpress site, all without a plugin. It’s very simple, and only takes a few steps and simple modification to your wordpress theme. If your uncomfortable with editing your theme, I have also included a way to do so without editing your theme – by using a plugin. Do note, however, that this works best, if your theme has a white or black background as its primary color. Hence, it may not work as well with some themes, compared to others. You should definitely still test it out anyways..
Adding code by editing your theme
Go to your WordPress theme editor, and open up the single.php
file. If you scroll down a little, you should see a loop for have_posts()
.Here is how the code looks in Twenty Sixteen theme. Yours might look slightly different.
// Start the loop. while ( have_posts() ) : the_post(); // Include the single post content template. get_template_part( 'template-parts/content', 'single' ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) { comments_template(); } ... ...
So based on the code above, if you wish for your toggle button for day and night mode to appear before your post content, you simply put the code right before the call to get_template_part( 'template-parts/content', 'single' );
.Scroll down all the way for the code.
Adding code without editing your theme
If you are uncomfortable with editing your theme, you can use a plugin to solve this problem. I have tried the Insert Post Ads plugin and it works fine. Install the plugin, the plugin shortcut will appear on the left hand navigation bar. Hover over it, and click Add New Post. Leave the Advert Title empty, and put the code below into the Advert Code.
<button onclick="toggleNightMode(this)">Night Mode</button> <script> function nightMode() { document.body.style.WebkitFilter = "invert(100%)"; var imgs = document.querySelectorAll("img"); for( var i = 0; i < imgs.length; i++ ) { imgs[i].style.WebkitFilter = "invert(0%)"; } } function dayMode() { document.body.style.WebkitFilter = "none"; var imgs = document.querySelectorAll("img"); for( var i = 0; i < imgs.length; i++ ) { imgs[i].style.WebkitFilter = "none"; } } function toggleNightMode(element) { if(element.innerHTML == "Night Mode") { nightMode(); element.innerHTML = "Day Mode"; } else { dayMode(); element.innerHTML = "Night Mode"; } } </script>
Now if you go to one of your posts, you will see a button like this
Conclusion
That’s it. If you need any help, let me know in the comments below !
Be First to Comment