This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Load different styles depending on the screen using the Strategy Pattern

function fofo_chrimbo_snippet() {

	if( function_exists( 'get_current_screen' ) ) {

		$current_screen = get_current_screen();

		/*

		Instead of using a switch (or if-else tree) to do something
		different depending on a specific value
		
		switch( $current_screen->id ) {

			case 'edit-post';
				$theme_style_slug = 'theme-style-slug-1';
				$theme_css_url = '/1/2/3';
				break;
			case 'post';
				$theme_style_slug = 'theme-style-slug-2';
				$theme_css_url = '/21/22/23';
				break;
			case 'edit-category';
				$theme_style_slug = 'theme-style-slug-3';
				$theme_css_url = '/31/32/33';
				break;
			case 'edit-post_tag';
				$theme_style_slug = 'theme-style-slug-4';
				$theme_css_url = '/41/42/43';
				break;
			case 'edit-page';
				$theme_style_slug = 'theme-style-slug-5';
				$theme_css_url = '/51/52/53';
				break;
			case 'page';
				$theme_style_slug = 'theme-style-slug-6';
				$theme_css_url = '/61/62/63';
				break;
		}

		wp_enqueue_style( $theme_style_slug, $theme_css_url );

		*/

		/* Use the strategy pattern and anonymous functions instead */

		$style_list_registry = [];
		$style_list_registry[ 'edit-post' ] = function() { wp_enqueue_style( 'theme-style-slug-1', '/1/2/3' ); };
		$style_list_registry[ 'post' ] = function() { wp_enqueue_style( 'theme-style-slug-2', '/21/22/23' ); };
		$style_list_registry[ 'edit-category' ] = function() { wp_enqueue_style( 'theme-style-slug-3', '/31/32/33' ); };
		$style_list_registry[ 'edit-post_tag' ] = function() { wp_enqueue_style( 'theme-style-slug-4', '/41/42/43' ); };
		$style_list_registry[ 'edit-page' ] = function() { wp_enqueue_style( 'theme-style-slug-5', '/51/52/53' ); };
		$style_list_registry[ 'page' ] = function() { wp_enqueue_style( 'theme-style-slug-6', '/61/62/63' ); };

		$style_list_registry[ $current_screen->id ]();

	}
}

add_action("admin_enqueue_scripts", "fofo_chrimbo_snippet");


About

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.