Set Default Dark Mode – Reign Theme

Get Started

Default Dark Mode for Reign Theme

This document provides a code snippet to enable dark mode by default for new visitors to your Reign theme website. The code sets the reign_dark_mode cookie automatically, allowing the site to remember the dark mode preference for future visits.

Instructions

Purpose

This code enables dark mode automatically for new visitors. If you set default_dark_mode to 1 (enabled), the site will load in dark mode by default and remember this preference using a cookie.

How to Use

  1. Add the code snippet below to your theme’s functions.php file or header.php file.
  2. Enable or disable dark mode by default by setting $default_dark_mode to 1 or 0, respectively.

Code Snippet

<?php
// Place this code in your theme's functions.php or header.php file

// Set default dark mode to 1 (enabled) or 0 (disabled) - currently hard-coded
$default_dark_mode = 1; // Change this to 0 to disable dark mode by default

if ( $default_dark_mode === 1 ) : ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Check if the reign_dark_mode cookie is already set
            if (!document.cookie.split('; ').find(row => row.startsWith('reign_dark_mode='))) {
                // Apply the dark-mode class and set the cookie to 'true' by default
                document.documentElement.classList.add('dark-mode');
                document.cookie = "reign_dark_mode=true; path=/; expires=" + new Date(Date.now() + 7 * 864e5).toUTCString();
            }
        });
    </script>
<?php endif; ?>

Explanation

  • Purpose: This code will enable dark mode by default if $default_dark_mode is set to 1.
  • To Disable Default Dark Mode: Set $default_dark_mode to 0.
  • Future Customization: To switch to a theme option, replace $default_dark_mode = 1; with $default_dark_mode = get_theme_mod( 'reign_default_dark_mode', false ); (update 'reign_default_dark_mode' as needed).

Future Enhancements

Once you are ready to use a theme option for dark mode, you can replace the hard-coded value with a theme mod like this:

$default_dark_mode = get_theme_mod( 'reign_default_dark_mode', false );

This will allow you to control dark mode directly through the WordPress Customizer settings.


With this setup, dark mode will activate by default on the first visit when $default_dark_mode is set to 1. The user’s preference will then be saved in a cookie for future visits.

Last updated: April 8, 2025