jrobinsonc
2/12/2020 - 4:58 PM

WordPress Plugin: Hide WP Admin Bar

WordPress Plugin: Hide WP Admin Bar

<?php
/*
Plugin Name: Hide WP Admin Bar
Plugin URI: https://gist.github.com/jrobinsonc/fd229cef8df0e38205c0b96f2e455d16
Description: Hides the WordPress admin bar by clicking on the logo of the admin bar.
Author: Jose Robinsosn
Version: 1.0
Author URI: https://joserobinson.com
*/

/**
 * Adds the styles for the plugin.
 *
 * @return void
 */
function hidewpadminbar_add_styles() {
	?>
	<style>
	#wpadminbar {
		transition: all 0.3s ease;
	}

	#wpadminbar.js-hide {
		width: 32px;
		min-width: 32px;
		overflow: hidden;
	}
	</style>
	<?php
}

/**
 * Adds the scripts for the plugin.
 *
 * @return void
 */
function hidewpadminbar_add_scritps() {
	?>
	<script>
	(function($wpadminbar, $wpAdminBarWpLogo){
		$wpAdminBarWpLogo.addEventListener('click', function(evt) {
			evt.preventDefault();

			let className = $wpadminbar.className;
			const isHidden = className.search('js-hide') !== -1;

			if (isHidden) {
				className = className.replace(/\s*js-hide\s*/, ' ');
			} else {
				className += ' js-hide';
			}

			$wpadminbar.className = className;
		});
	})(
		document.querySelector('#wpadminbar'),
		document.querySelector('#wp-admin-bar-wp-logo')
	);
	</script>
	<?php
}

/**
 * Initializes the plugin.
 *
 * @return void
 */
function hidewpadminbar_init() {
	if ( is_admin() || ! is_user_logged_in() ) {
		return;
	}

	add_action( 'wp_head', 'hidewpadminbar_add_styles', 9999, 0 );
	add_action( 'wp_footer', 'hidewpadminbar_add_scritps', 9999, 0 );
}

add_action( 'plugins_loaded', 'hidewpadminbar_init' );