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?

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.

  • 2
    is_admin() is not necessary here – Pieter Goosen Nov 4 '15 at 4:31
  • 1
    @PieterGoosen Agreed, running the function without the is_admin() and it works just fine. – erwstout Nov 4 '15 at 15:32
  • 1
    You're right. I'm not entirely sure what I was thinking there. – Pat J Nov 4 '15 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, privacy policy and cookie policy

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