如何在WordPress网站上添加暗黑模式(不使用插件)
这篇文章主要介绍如何在WordPress网站中实现暗黑模式,而不需要使用插件或第三方库。以下是具体步骤:
- 复制下面的代码,并将其添加到您的WordPress网站的functions.php文件中。
function cwpai_darkmode_shortcode() {
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$darkmode = get_user_meta($user_id, 'cwp_dark', true);
if ($darkmode == 1) {
$checked = 'checked';
} else {
$checked = '';
}
$output = '<input type="checkbox" id="cwp_darkmode" name="cwp_darkmode" value="1" ' . $checked . '>';
$output .= '<label for="cwp_darkmode">Dark Mode</label>';
$output .= '<script>
jQuery(document).ready(function($) {
$("#cwp_darkmode").change(function() {
var darkmode = $(this).prop("checked");
if (darkmode == true) {
var darkmode = 1;
} else {
var darkmode = 0;
}
$.ajax({
type: "POST",
url: "' . admin_url('admin-ajax.php') . '",
data: {
action: "cwpai_darkmode",
darkmode: darkmode
},
success: function(data) {
if (darkmode == 1) {
$("body").addClass("cwp_dark");
} else {
$("body").removeClass("cwp_dark");
}
}
});
});
});
</script>';
} else {
if (isset($_COOKIE['cwp_dark'])) {
$checked = 'checked';
} else {
$checked = '';
}
$output = '<input type="checkbox" id="cwp_darkmode" name="cwp_darkmode" value="1" ' . $checked . '>';
$output .= '<label for="cwp_darkmode">Dark Mode</label>';
$output .= '<script>
jQuery(document).ready(function($) {
$("#cwp_darkmode").change(function() {
var darkmode = $(this).prop("checked");
if (darkmode == true) {
document.cookie = "cwp_dark=1; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
$("body").addClass("cwp_dark");
} else {
document.cookie = "cwp_dark=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
$("body").removeClass("cwp_dark");
}
});
});
</script>';
}
return $output;
}
add_shortcode('darkmode', 'cwpai_darkmode_shortcode');
function cwpai_darkmode_ajax() {
$user_id = get_current_user_id();
$darkmode = $_POST['darkmode'];
update_user_meta($user_id, 'cwp_dark', $darkmode);
die();
}
add_action('wp_ajax_cwpai_darkmode', 'cwpai_darkmode_ajax');
add_action('wp_ajax_nopriv_cwpai_darkmode', 'cwpai_darkmode_ajax');
function cwpai_darkmode_body_class($classes) {
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$darkmode = get_user_meta($user_id, 'cwp_dark', true);
if ($darkmode == 1) {
$classes[] = 'cwp_dark';
}
} else {
if (isset($_COOKIE['cwp_dark'])) {
$classes[] = 'cwp_dark';
}
}
return $classes;
}
add_filter('body_class', 'cwpai_darkmode_body_class');
-
在需要添加暗黑模式的页面或文章中使用短代码[ darkmode ]。
-
如果用户已登录,他们的偏好设置将保存在WordPress数据库中。如果用户未登录,则使用cookie保存偏好设置。
-
根据用户的偏好设置,网站的背景颜色将自动切换。同时,您也可以使用CSS样式表来自定义暗黑模式的外观。
-
如果您想要进一步优化性能,可以将jQuery从短代码中移除,并将其加入到网站的页脚中。同时,您也可以使用CSS样式表来美化暗黑模式的开关按钮。
希望这些步骤能够帮助您成功地添加暗黑模式功能到您的WordPress网站中。
原文地址: https://www.cveoy.top/t/topic/n6rg 著作权归作者所有。请勿转载和采集!