How to get a list of all registered style-sheets in WordPress

  • admin
  • Tag 1
    Tag 2
    Tag 3
    Tag 4

    As a WordPress developer, I work with Themes and plugins a LOT. In fact, that’s about 98% of the work I do. One of the things that can be quite frustrating, is when a developers code utilizes CSS that is poorly written. This makes it hard or even impossible to over-write. In these cases, it’s often easiest to just de-queue their style sheets, and write my own css. However, to de-queue a style sheet, you also need to know what handle it’s hooked under. That means digging into the code to find where and how it’s hooked. This in itself can be quite time consuming. So one day I came up with an idea: why not just sift through a list of all registered style sheets, and find the handle that way? After some searching, I just couldn’t find a solution for this problem, so I wrote one myself.

    First, we hook into the same action hook that WordPress uses to register and enqueue style sheets. My logic here was that since this is where they are registered, we can use the same hook to list all the files it has registered. So first we put in our hook:

    add_action( 'wp_enqueue_scripts', 'list_all_sheets', 999); //
    

    Notice the 999. This is the priority at which this action will fire. You can set it to earlier with a lower number, but some plugins and themes register their sheets at higher priorities, so it doesn’t hurt to set this number higher, to make sure we run it AFTER all sheets are registered.

    Next we have the function:

    	function list_all_sheets () {
    		
    		   global $wp_styles;
    		   
    		   foreach ($wp_styles as $style) {
    		   					
    		   		foreach ($style as $s) {
    		   				
    					echo "<li>Source:$s->src</li>";
    				   	echo "<li>Handle:$s->handle</li>";
    					
    				}
    		   }
    		   	
       
    	}
    

    Now one thing of note, the $wp_styles is an Object, with an array of each registered sheet within it. We can easily iterate through, and spew out the information we need. There is other information within it as well, but for the sake of this article, I’m only displaying the information that’s relevant. One last note, some style sheets might be especially tough to get rid of, if they are queued using the wrong method. In these very special cases, you can hook into WordPresses wp_print_styles() action instead. It’s really not recommended to use this hook, however in extreme cases it can be justified.

    Leave a comment

  • (required)