Can I add styles to footer with $wp_styles->add_data?

I’m working on a script to easily move js and css scripts to the footer using the add_data function in $wp_scripts and $wp_styles. I know for scripts that if the group is greater than 0 the script call will be moved to the footer (first foreach below does that). However, setting the group for styles doesn’t have the same effect (and group is set properly with second foreach). Is there a way to move styles to the footer with the same method, or should I be looking for an alternative?

function mod_scripts(){
    global $wp_scripts, $wp_styles;
    foreach($wp_scripts->queue as $script){
        if ( ! $wp_scripts->get_data( $script, 'group' ) ){
            $wp_scripts->add_data( $script, 'group', 1 );
        }
    }
    foreach($wp_styles->queue as $style){
        if ( ! $wp_styles->get_data( $style, 'group' ) ){
            $wp_styles->add_data( $style, 'group', 1 );
        }       
    }
}

EDIT: The reason for the request is that I’m trying to remove blocking css to make a page load faster. The recommended method is basically to just embed the css directly into the page, but that’s never worked out well. And now I realize that the question as I asked it is flawed. I’m just looking for an effective way to load styles that still maintains proper compatibility with plugins.

7 s
7

I don’t know what your exact reason is for this, but you should scrap the idea of moving styles to the footer. If you though of a gain in speed, you might gain a unnoticable amount, if any, but that will be at the cost of other bigger things.

Styles should always be added inside the <head></head> tag. The reason is that <style> tags outside the head tags are invalid HTML. That is why you don’t have that option to load styles in the footer with wp_enqueue_style and wp_register_style like you have with scripts.

I would seriously rethink this whole idea.

EDIT

As a sidenote from a comment to this answer from @G.M.

wp_enqueue_style add <link> tag, not <style> one. However, <link> tag is not allowed outside <head> too

Leave a Comment