Categories
Advanced Tutorials

Implementing a Light/Dark Theme Toggle with GeneratePress

Introduction

In this tutorial, we’ll walk through the steps to add a light/dark theme toggle to your website using the GeneratePress theme. This feature enhances user experience by allowing visitors to switch between themes according to their preferences.

Prerequisites

  • Basic knowledge of JavaScript and CSS.
  • A WordPress website with the GeneratePress theme installed.

Step 1: Understanding the Code

First, let’s break down the provided JavaScript and CSS code.

JavaScript Code Explanation
  • UUID.themes: This object holds the color schemes for dark and light themes.
  • UUID.applyTheme(): A function to apply the selected theme by changing CSS variables.
  • UUID.toggleLogo(): Changes the website logo depending on the theme.
  • Initial Theme Setup: Checks for saved themes or system preferences and applies them.
  • Theme Switch Event Listener: Toggles the theme when the switch is clicked.
var UUID = UUID || {};
var $ = jQuery || {};
UUID.themes = {
dark_theme: {
'--primary': '#5c5af2',
'--contrast': '#ffffff',
'--contrast-2': '#f7f8f9',
'--contrast-3': '#f0f0f0',
'--base': '#b2b2be',
'--base-2': '#575760',
'--base-3': '#222222',
'--base-4': '#242628',
'--base-5': '#202020',
},
light_theme: {
'--primary': '#5c5af2',
'--contrast': '#222222',
'--contrast-2': '#242628',
'--contrast-3': '#202020',
'--base': '#ffffff',
'--base-2': '#f7f8f9',
'--base-3': '#f0f0f0',
'--base-4': '#b2b2be',
'--base-5': '#575760',
}
};
UUID.applyTheme = function( themeName ) {
var theme = UUID.themes[ themeName ];
$.each( theme, ( key, value ) => {
$( ':root' ).css( key, value );
} );
};
UUID.toggleLogo = function( themeName ) {
var logoSrc = themeName === 'light_theme'
? 'https://domain.com/assets/img/black-logo.webp'
: 'https://domain.com/assets/img/white-logo.webp';
$( '.site-logo img, .sticky-navigation-logo img' ).prop( 'src', logoSrc ).prop( 'srcset', '' );
}
;( function( $ ) {
var $primaryMenu = $( '#primary-menu' );
var $themeSwitch = $primaryMenu.find( '#theme-switch');
var $themeSwitchCheckbox = $primaryMenu.find( 'input[name="theme-switch-checkbox"]' );
var savedTheme = localStorage.getItem( 'uuid_theme' );
var isDarkMode = window.matchMedia && window.matchMedia( '(prefers-color-scheme: dark)' ).matches;
var prefersColorScheme = '';
if ( savedTheme ) {
$( 'body' ).addClass( savedTheme );
if ( $themeSwitchCheckbox.is( ':checked' ) ) {
$themeSwitchCheckbox.prop( 'checked', false );
$( 'body' ).removeClass( 'dark_theme' );
} else {
$themeSwitchCheckbox.prop( 'checked', true );
$( 'body' ).addClass( 'dark_theme' );
}
UUID.applyTheme( savedTheme );
UUID.toggleLogo( savedTheme );
} else {
if ( isDarkMode ) {
prefersColorScheme = 'dark_theme';
} else {
prefersColorScheme = 'light_theme';
}
UUID.applyTheme( prefersColorScheme );
UUID.toggleLogo( prefersColorScheme );
}
$themeSwitch.on( 'click', function() {
$themeSwitchCheckbox = $( this ).find( 'input[name="theme-switch-checkbox"]' );
if ( $themeSwitchCheckbox.is( ':checked' ) ) {
$themeSwitchCheckbox.prop( 'checked', false );
$( 'body' ).removeClass( 'dark_theme' );
} else {
$themeSwitchCheckbox.prop( 'checked', true );
$( 'body' ).addClass( 'dark_theme' );
}
var $currentTheme = $( 'body' ).hasClass( 'dark_theme' ) ? 'light_theme' : 'dark_theme';
localStorage.setItem( 'uuid_theme', $currentTheme );
UUID.applyTheme( $currentTheme );
UUID.toggleLogo( $currentTheme );
} );
} )( jQuery);
CSS Code Explanation
  • .theme-switch-wrapper: Styles the theme switch container.
  • .theme-switch: Hides the checkbox and styles the slider.
  • Transition Effects: Adds smooth transitions when the theme is switched.
/**
* Toggle button for dark and light theme.
*/
.theme-switch-wrapper {
display: flex;
align-items: center;
justify-content: center;
margin: 20px;
}
.theme-switch input {
display: none;
}
.theme-switch .slider {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
background-color: rgba(0, 0, 0, 0.25);
border-radius: 34px;
cursor: pointer;
transition: background-color 0.2s;
}
.theme-switch .slider:before {
content: "";
position: absolute;
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: rgba(255, 255, 255, 0.25);
border-radius: 50%;
transition: transform 0.2s;
}
.theme-switch input:checked + .slider {
background-color: var(--accent);
}
.theme-switch input:checked + .slider:before {
transform: translateX(26px);
}
.theme-switch .slider.round {
border-radius: 34px;
}
.theme-switch .slider.round:before {
border-radius: 50%;
}

Step 2: Adding the Toggle HTML Code

  1. Open your WordPress dashboard.
  2. Navigate to Appearance > Theme Editor.
  3. Select the functions.php file.
  4. Paste the JavaScript code at the end of the file.
  5. Click Update File.
<?php/**
 * Add the toggle button the primary main menu for WordPress.
 */
function uuid_add_theme_switch_toggle( $items, $args ) {
	if ( $args->theme_location === 'primary' ) {
		$items .= '<div id="theme-switch" class="theme-switch-wrapper">
			<label for="theme-switch-checkbox" class="theme-switch">
				<input type="checkbox" id="theme-switch-checkbox" name="theme-switch-checkbox" />
				<div class="slider round"></div>
			</label>
		</div>';
	}
	
	return $items;
}

add_filter( 'wp_nav_menu_items', 'uuid_add_theme_switch_toggle', 10, 2 );

Step 3: Integrating the CSS

  1. In the Theme Editor, select the style.css file.
  2. Add the provided CSS code for the theme switch.
  3. Update the file.

Step 4: Adding the Toggle Button

  • The provided PHP function uuid_add_theme_switch_toggle() adds the toggle button to the primary menu.
  • Add this function to your functions.php file.

Step 5: Testing

  • Visit your website and ensure the toggle appears in the primary menu.
  • Test the toggle to switch between light and dark themes.
  • If you already have a building site and have used only the Block editor to build your site you have used var(–color-name) in your custom stylesheet files then you won’t need to make many changes to make the dark/light theme look good.

Conclusion

Congratulations! You’ve successfully added a theme toggle to your GeneratePress website. This feature not only improves aesthetics but also enhances accessibility and user experience.

Troubleshooting

If you encounter issues:

  • Check for any syntax errors in the code.
  • Ensure that the JavaScript and CSS codes are correctly placed.
  • Clear your browser cache to see the changes.

Leave a Reply

Your email address will not be published. Required fields are marked *