2

I'm building a custom theme for a client and I've been adding stylesheets incorrectly for a while, so I decided to do it the correct way :-).

However, when I add the stylesheet to my functions.php file like so:

wp_enqueue_style('theme-styles', get_template_directory_uri() . '/css/all.css', array(), false , 'all');

It also is applying to the Wordpress Admin panel. My link colors and fonts change, and there are some layout issues as well.

If I enqueue it inside of a function like this:

function theme_styles(){
        wp_enqueue_style('theme-styles', get_template_directory_uri() . '/css/all.css', array(), false , 'all');
    }
    add_action( 'wp_enqueue_scripts', 'theme_styles' );

It does not change the admin panel at all, which is good. So my question is, when researching and reading about how to enqueue stylesheets no articles mention adding styles to a function. Scripts, yes, but not styles. What is the correct way to do it to avoid changing my admin styles?

2 Answers 2

3

You could do it like this:

function theme_styles(){
    /*
     * This if() statement is unnecessary, as wp_enqueue_scripts
     * doesn't fire on the admin pages.
     * if( is_admin() ) {
     *   return;
     * }
     */
    wp_enqueue_style(
        'theme-styles', 
        get_template_directory_uri() . '/css/all.css', 
        array(), 
        false,
        'all'
    );
}
add_action( 'wp_enqueue_scripts', 'theme_styles' );

References

Also, note that the wp_enqueue_scripts hook is used to enqueue both scripts and styles.

3
  • 2
    is_admin() is not necessary here Nov 4, 2015 at 4:31
  • 1
    @PieterGoosen Agreed, running the function without the is_admin() and it works just fine.
    – erwstout
    Nov 4, 2015 at 15:32
  • 1
    You're right. I'm not entirely sure what I was thinking there.
    – Pat J
    Nov 4, 2015 at 20:26
3

Enqueueing styles within a function as you have done is the standard best practice for WordPress, whether you are building a theme or creating a child theme. And as mentioned, you can enqueue both styles and scripts from within one function, http://marker.to/65CMY3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.