[ad_1]
[ad_2]
I don’t know how about you, but I have a lot of plugins and they really like to display notices in backend. Some are nice and easy to close without page refresh, but other require page refresh and really like to come back. So I made simple code to add a toggle in the admin menu bar: “(Un)hide”. Add the following code to functions.php:
// Add a button to the WordPress admin bar
function add_toggle_notices_button($admin_bar) {
if (!is_admin()) {
return;
}
$admin_bar->add_node(array(
'id' => 'toggle_notices',
'title' => '(Un)hide',
'href' => '#',
'meta' => array(
'class' => 'toggle-notices',
'title' => 'Toggle Notices Visibility',
),
));
}
add_action('admin_bar_menu', 'add_toggle_notices_button', 999);
// Add custom script and styles
function toggle_notices_script() {
if (!is_admin()) {
return;
}
?>
<style>
#wpadminbar .toggle-notices { cursor: pointer; }
.custom-hide-notice { display: none !important; }
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to hide notices and set local storage
function hideNotices() {
const notices = document.querySelectorAll('.notice, .update-nag, [class*="updated"]');
notices.forEach(function(notice) {
notice.style.display = 'none';
notice.classList.add('custom-hide-notice');
});
localStorage.setItem('notices_hidden', 'true');
}
// Function to show notices and update local storage
function showNotices() {
const notices = document.querySelectorAll('.notice, .update-nag, [class*="updated"]');
notices.forEach(function(notice) {
notice.style.display = 'block';
notice.classList.remove('custom-hide-notice');
});
localStorage.setItem('notices_hidden', 'false');
}
// Check local storage to see if notices were hidden
function checkNoticesState() {
const noticesHidden = localStorage.getItem('notices_hidden');
if (noticesHidden === 'true') {
hideNotices();
} else {
showNotices();
}
}
// Add click event listener to the button
const button = document.getElementById('wp-admin-bar-toggle_notices');
if (button) {
button.addEventListener('click', function(e) {
e.preventDefault();
const noticesHidden = localStorage.getItem('notices_hidden');
if (noticesHidden === 'true') {
showNotices();
} else {
hideNotices();
}
});
}
// Check notices state on load
checkNoticesState();
});
</script>
<?php
}
add_action('admin_footer', 'toggle_notices_script');
