Solution with cookie [wordpress]
You will need jQuery cookie plugin.
Create javascript file "themechanger.js":
(function($){
var theme = $.cookie("styles");
var themehref = document.getElementById(theme_styles.rel_id);
setTheme = function(mode){
if (theme == mode)
return;
if (mode == 'light') {
$.cookie('styles', mode);
themehref.href = theme_styles.light;
}
else if (mode == 'dark') {
$.cookie('styles', mode);
themehref.href = theme_styles.dark;
}
}
})(jQuery);
In functions.php
enqueue styles and javascript:
add_action('init', 'load_styles', 15);
function load_styles() {
$current_style = '/styleSheetLightTheme.css';
if ( isset($_COOKIE['styles']) && $_COOKIE['styles'] == "dark")
$current_style = '/styleSheetDarkTheme.css';
wp_register_style( 'stylename', get_stylesheet_directory_uri() . $current_style );
wp_enqueue_style( 'stylename');
wp_enqueue_script( 'jquery_cookie', get_template_directory_uri() . '/js.cookie.js', ['jquery'] );
wp_register_script( 'theme_script', get_template_directory_uri() . '/themechanger.js', ['jquery', 'jquery_cookie'] );
//
// object "theme_styles" will store links to style, used in javascript
wp_localize_script( 'theme_script', 'theme_styles', [
'light' => get_stylesheet_directory_uri() . '/styleSheetLightTheme.css',
'dark' => get_stylesheet_directory_uri() . '/styleSheetDarkTheme.css',
'rel_id' => 'stylename-css',
]);
wp_enqueue_script('theme_script');
}
To change theme style use javascript function setTheme()
<a href="javascript:;" onClick="setTheme('dark'); return false;">Dark Theme</a><br>
<a href="javascript:;" onClick="setTheme('light'); return false;">Light Theme</a>
Local storage [for your code]:
<html>
<head>
<link id="my_style" rel="stylesheet" type="text/css" href="styleSheetLightTheme.css">
</head>
<body>
<script>
var theme = localStorage.getItem('styles');
var themehref = document.getElementById('my_style');
var base_url = 'styleSheet{{mode}}.css';
// default value
if(!theme)
localStorage.setItem('styles','light');
if (theme == 'dark')
themehref.href = base_url.replace('{{mode}}', 'DarkTheme');
else
themehref.href = base_url.replace('{{mode}}', "LightTheme");
function setTheme(mode){
if ( (mode != 'light' && mode != 'dark'))
return;
theme = localStorage.getItem('styles');
// don't change if it's already active
if (mode == theme)
return;
if (mode == 'light') {
localStorage.setItem('styles', 'light');
themehref.href = base_url.replace('{{mode}}', 'LightTheme');
}
else if (mode == 'dark') {
localStorage.setItem('styles', 'dark');
themehref.href = base_url.replace('{{mode}}', 'DarkTheme');
}
}
</script>
<a href="javascript:;" onClick="setTheme('dark'); return false;">Dark Theme</a>
|
<a href="javascript:;" onClick="setTheme('light'); return false;">Light Theme</a>
</body>
</html>