WordPress Script Debugging

Code I used for echoing out the WordPress enqueued scripts and styles into the JS console (here).

Tl;DR

So I recently noticed that when developing child themes some of my CSS was being overwritten by the parent theme. This makes sense because according to WordPress’s developer resources: “the child theme is loaded before the parent theme“. Although that may work in many cases, this wasn’t going to cut it for mine.

I wrote a custom function to enqueue first the parent theme THEN the child theme so that the CSS from the child theme would be read latest and overwrite some of the rules of the parent. Done! Great! Wow! … Not quite…

This lead to a problem of a duplicate child stylesheet being loaded, which in most circumstances wouldn’t cause too much of an issue but in this case it caused errors when performing minor updates. The WordPress generator was stuck enqueuing an older version of my stylesheet along with the update. Needless these two running in congruence caused several issues.

I used some code from Lakewood echo out the scripts and styles enqueued by WordPress so I could find the duplicate script handle and dequeue it. Simple enough! I slapped it in there but unfortunately my duplicate problem stylesheet persisted.

Not to worry. Doing some digging I found that with messing with the priority of the enqueue/dequeue I was able to successfully remove the duplicate. I had to dequeue the duplicate after it was enqueued but before my custom one had enqueued. Anyways thanks for reading.

Code

Function to echo out enqueued scripts and styles.

/**
 * Print enqueued style/script handles
 * https://lakewood.media/list-enqueued-scripts-handle/
 * Modified by Chris Fust for a more JS friendly
 * readabily thing.
 */
function lakewood_print_scripts_styles() {
    if( !is_admin() && is_user_logged_in() && current_user_can( 'manage_options' )) {

        // push scripts and styles to arrays
        // so that they appear in the JSON
        // in the order they would enqueue
        // with wp_enqueue_*()

        // local vars
        $scripts = [];
        $styles = [];

        // Print Scripts
        global $wp_scripts;
        foreach( $wp_scripts->queue as $handle ) :
           $scripts[] = array( $handle => $wp_scripts->registered[$handle]->src );
        endforeach;

        // Print Styles
        global $wp_styles;
        foreach( $wp_styles->queue as $handle ) :
           $styles[] = array( $handle => $wp_styles->registered[$handle]->src );
        endforeach;

        // echo out scripts and styles
        // as separate objects
        echo '<script>';
        echo 'console.log({ "scripts" : ' . json_encode( $scripts ) . '});';
        echo 'console.log({ "styles" : ' . json_encode( $styles ) . '});';
        echo '</script>';
    }
}
// This is primarily used for debugging so
// I'm going to skip adding this function to the queue
// add_action( 'wp_print_scripts', 'lakewood_print_scripts_styles', 101 );