Load CSS on specific pages

You can optimise how Microthemer loads CSS by assigning folders to specific pages, or types of page. Microthemer does this automatically if the Auto folder option in the footer is enabled. But you may want to customise the default condition, which tends to assign a folder to just one page.

00:00 Introduction
00:13 Benefit 1: Page speed optimisation
00:45 Benefit 2: Styles only apply where intended (alternative to page-id)
1:16 Benefit 3: Load CSS in the admin area
1:29 Folders load globally by default
2:14 Assign a folder to load on a single page
4:13 Assign a folder to load on multiple pages
4:42 Exclude a folder from certain pages
5:50 Supported WordPress and Microthemer PHP functions
6:46 Defer non-critical CSS loading to maximise page speed
8:15 Loading styles in the admin area for Gutenberg consistency
10:54 Style the WordPress dashboard with regular point and click editing
13:51 Related upcoming features

Examples

CSS loading is controlled by PHP-like logical conditions, which Microthemer can help you generate. The following table provides examples of supported conditions. If a condition is evaluated as true on a given page, it means the folder will load its CSS.

Example conditionThe condition will evaluate as TRUE if:
is_page(3)It is a Page with an id of “3”
is_page(‘about-me’)It is a Page with the slug “about-me”
is_single()It is a single Post
is_page() or (is_single() and !is_single(9))It is a Page or a single Post without an id of 9
is_page() and !is_page(4)It is a Page, but the id is NOT “4”
is_categoy()It is a Category archive of multiple Posts
has_category(‘News’)It is a single Post with the Category “News”
is_user_logged_in()The user is logged in
get_post_type() === “testimonial”The Post has a type of “testimonial”
!is_single(5) and !is_single(6) It is not a single Post with the id “5”, or “6”
isset($_GET[‘message_sent’]) The URL has a “message_sent” parameter

Function Reference

Microthemer does NOT use the PHP eval() function. Instead, it reads your conditions as plain text and then runs the relevant function(s). Only a handful of PHP functions are allowed – some WordPress API functions, custom Microthemer functions, and native PHP, namely $_GET and isset().

Note: the result of each function or overall condition is cached so that you can freely repeat the same functions and conditions in multiple folders without incurring any performance penalty.

Supported WordPress Functions

Custom Microthemer Functions

\Microthemer\has_template()

This can be used to check if a particular Bricks template or Gutenberg template, template part, pattern, or navigation is loading on the current page. For block themes, Microthemer maintains a cache of templates/parts/patterns/navigation. This ensures that has_template() can run very efficiently even when checking for templates nested inside other templates.

Microthemer generates has_template() conditions automatically when you style individual templates, template parts, patterns, and navigation via the Full Site Editor (FSE). Watch the walk-through video to see how Microthemer integrates with the Gutenberg block editor.

Usage Examples

  • \Microthemer\has_template(‘bricks’, 4196, ‘Contact form’)
  • \Microthemer\has_template(‘wp_template’, ‘search’, ‘Search page’)
  • \Microthemer\has_template(“wp_template”, “page-wide”, “Wide page”)
  • \Microthemer\has_template(‘wp_template_part’, ‘header’, ‘Header’)
  • \Microthemer\has_template(“wp_template_part”, “footer”, “Footer”)
  • \Microthemer\has_template(‘wp_pattern’, ‘business’, ‘Business page content’)
  • \Microthemer\has_template(“wp_pattern”, 4537, “Testimonials”)
  • \Microthemer\has_template(‘wp_navigation’, 4324, ‘Main menu’)
  • \Microthemer\has_template(“wp_navigation”, 4586, “Support menu”)

Source code

function has_template($source = null, $id = null, $label = null){

	global $post;

	$cache = !empty(Logic::$cache[$source]['template_ids'])
		? Logic::$cache[$source]['template_ids']
		: false;
	$template_ids = $cache ?: array();
	$returnType = true;

	if (!$source || !$id){
		return false;
	} if ($cache){
		return !empty($cache[$id]) ? $cache[$id] : false;
	}

	// gather template_ids
	switch ($source) {

		case 'bricks':
			if (method_exists('\Bricks\Helpers', 'render_with_bricks')){
				if (\Bricks\Helpers::render_with_bricks($post->ID)) {
					foreach (\Bricks\Database::$active_templates as $content_type => $template_id){
						Logic::getBricksTemplateIds($template_id, $template_ids, $content_type);
					}
				}
			}
			break;

		case 'wp_template':
		case 'wp_template_part':
		case 'wp_pattern':
		case 'wp_navigation':
			$returnType = 'blocksOnly';
			Logic::getGutenbergTemplateIds($source, $id,$template_ids);
			break;
	}

	// cache template analysis for the source
	Logic::$cache[$source]['template_ids'] = $template_ids;

	return !empty($template_ids[$id]) ? $returnType : false;
}

\Microthemer\is_active()

Check if a theme or plugin is active. Enter the type of item to check as the first parameter. Enter the directory name of the theme inside /wp-content/themes or the plugin inside /wp-content/plugins.

Usage Examples

  • \Microthemer\is_active(‘theme’, ‘twentytwentythree’)
  • \Microthemer\is_active(‘plugin’, ‘microthemer’)
  • \Microthemer\is_active(‘plugin’, ‘wp-rocket’)

Source code

function is_active($item = null, $slug = null){
   switch ($item) {
      case 'plugin':
	$active_plugins = get_option('active_plugins', array());
	foreach($active_plugins as $path){
	   if (strpos($path, $slug) !== false){
	      return true;
	   }
	}
        return is_plugin_active_for_network($slug);
      case 'theme':
	   $theme = wp_get_theme();
	   return $theme->get_stylesheet() === $slug;
      default:
	   return false;
   }
}

\Microthemer\is_post_or_page()

Check if you are on a post or a page, on either the frontend or the block editor. The latter could mean viewing the page via the regular “Edit Page” admin screen or via the Full Site Editor (FSE). This is useful because you will normally want any custom Microthemer CSS to render in all contexts. Microthemer uses this condition when targeting single pages if you have “Auto folder” enabled with the “Page” option.

Most of the time, you will pass a single post/page ID parameter. But you can also pass “global” as a parameter to load your folder on all pages and single posts. Or you can pass “front” to load the folder on the home page, including any Full Site Editor (FSE) pages that default to the home page.

Usage Examples

  • \Microthemer\is_post_or_page(45)
  • \Microthemer\is_post_or_page(“global”)
  • \Microthemer\is_post_or_page(“front”)

Source code

function is_post_or_page($id = null){

	$globalOrFrontMatch = ($id === 'front' && Helper::isFrontOrFallback()) ||
	                      ($id === 'global' && (is_public() || Helper::isBlockAdminPage('global')));
	
	return is_public() && (is_page($id) || is_single($id) || $globalOrFrontMatch)
		? true
		: (is_admin() && (Helper::isBlockAdminPage($id) || $globalOrFrontMatch )
			? 'blocksOnly'
			: false);
}

\Microthemer\is_admin_page()

Check if the current page is any admin page, or a specific admin page. Optionally pass in a single parameter that can either be a PHP file name or a post id. If no parameter is passed in, the function will return true if it is any admin area page.

Usage Examples

  • \Microthemer\is_admin_page()
  • \Microthemer\is_admin_page(4)
  • \Microthemer\is_admin_page(‘edit.php’)

Source code

function is_admin_page($pageNameOrId = false){

   return is_admin() 
      && !$pageNameOrId
      || (
            isset($GLOBALS['pagenow']) 
            && $GLOBALS['pagenow'] === $pageNameOrId
          )
      || (
            is_numeric($pageNameOrId) 
            && isset($_GET['post']) 
            && intval($_GET['post']) === intval($pageNameOrId)
          );
}

\Microthemer\is_public()

Check if the current page is a public facing page (i.e. the frontend, not the admin area). This function does not accept any parameters.

Usage Example

  • \Microthemer\is_public()

Source code

function is_public(){
  
   return !is_admin();
}

\Microthemer\is_public_or_admin()

Checks if the current page is on the admin side or the frontend. If no parameter is passed in, it will always return true. If a Post or Page id is passed in, it will return true on the admin and frontend for a specific post or page only. This function is useful when you want styles to appear in the Gutenberg editor as well as the frontend. Support for that must be enabled via the Preferences however. And watch the video for advice about targeting elements with single classes.

Usage Examples

  • \Microthemer\is_public_or_admin()
  • \Microthemer\is_public_or_admin(5)

Source code

function is_public_or_admin($postOrPageId = null){
   
   return !$postOrPageId
      || ( 
            !is_admin() && (is_page($postOrPageId) || is_single($postOrPageId)) 
         )
      || is_admin_page($postOrPageId);
}

\Microthemer\match_url_path()

Check if the URL path for the current page contains a text substring, or matches regex pattern if the second argument is set to true.

Usage Examples

  • \Microthemer\match_url_path(‘about’)
  • \Microthemer\match_url_path(‘^\/support’, true)
  • \Microthemer\match_url_path(‘^\/contact\/$’, true)
  • \Microthemer\match_url_path(‘^\/forum\/users\/.+?\/’, true)

Source code

function match_url_path($value = null, $regex = false){
   $urlPath = $_SERVER['REQUEST_URI'];
   return $regex
      ? preg_match('/'.$value.'/', $urlPath)
      : strpos($urlPath, $value) !== false;
}

\Microthemer\query_admin_screen()

Check the value of a WP Screen object property by passing in a property key and value to compare. This function is useful for applying styles to all sorts of admin pages.

Usage Examples

  • \Microthemer\query_admin_screen()
  • \Microthemer\query_admin_screen(‘action’, ‘add’)
  • \Microthemer\query_admin_screen(‘base’, ‘edit’)
  • \Microthemer\query_admin_screen(‘is_block_editor’, true)
  • \Microthemer\query_admin_screen(‘post_type’, ‘post’)
  • \Microthemer\query_admin_screen(‘taxonomy’, ‘category’)

Source code

function query_admin_screen($key = null, $value = null){

   if (!function_exists('get_current_screen')){
      return false;
   }

   $current_screen = get_current_screen();

   return (
             $key === null || isset($current_screen->$key)
          )
       && (
             $value === null || $current_screen->$key === $value
          );
}

\Microthemer\user_has_role()

If no parameter is passed in, this simply checks if the current user is logged in. Pass in a user ID value to check for a specific user, or a role name to check for a type of user.

Usage Examples

  • \Microthemer\user_has_role()
  • \Microthemer\user_has_role(1)
  • \Microthemer\user_has_role(345)
  • \Microthemer\user_has_role(‘subscriber’)
  • \Microthemer\user_has_role(‘contributor’)
  • \Microthemer\user_has_role(‘author’)
  • \Microthemer\user_has_role(‘editor’)
  • \Microthemer\user_has_role(‘administrator’)

Source code

function user_has_role($roleOrUserId = null){
	return is_user_logged_in() && $roleOrUserId === null ||
	       wp_get_current_user()->roles[0] === $roleOrUserId ||
	       (is_numeric($roleOrUserId) && intval($roleOrUserId) === get_current_user_id());
}
Close