0

I have a pretty large style.css file. A lot of the content is only needed for certain pages.

I thought it might be a good idea to just call them with "if queries" when they're necessary.

I only started, but my header.php already feels bloated:

<?php
    if (is_page([505,981,928,1035,1036]))
        echo '<link href="/wp-content/themes/alltuts/start-here.css" rel="stylesheet" type="text/css">'; ?>

<?php
    if (is_page([37,40]))
        echo '<link href="/wp-content/themes/alltuts/faq-links.css" rel="stylesheet" type="text/css">'; ?>
<?php
    if (is_page('27'))
        echo '<link href="/wp-content/themes/alltuts/contact-form.css" rel="stylesheet" type="text/css">'; ?>

<?php
    if (is_front_page())
        echo '<link href="/wp-content/themes/alltuts/slider.css" rel="stylesheet" type="text/css">'; ?>

Now, before I continue I wonder if this is actually the correct way to do it in Wordpress or will this even slow down performance in the end? If so, shall I just leave everything in my main style.css?

1

Instead of directly outputting the stylesheets to your header, you should use wp_enqueue_stylesheet. Take a look at this example:

add_action( 'wp_enqueue_scripts', 'my_scripts' );
function my_scripts(){
    if (is_page([505,981,928,1035,1036]))
        wp_enqueue_style( 'css1', get_template_directory_uri().'/start-here.css');

    if (is_page([37,40]))
        wp_enqueue_style( 'css2', get_template_directory_uri().'/faq-links.css.css');

    if (is_page('27'))
       wp_enqueue_style( 'css3', get_template_directory_uri().'/contact-form.css');

    if (is_front_page())
       wp_enqueue_style( 'css4', get_template_directory_uri().'/slider.css');
}

This way, you don't have to mess with your header.php file in any way, and you make sure your approach is in an standard way.

For example, if you are developing a commercial theme, most of the markets won't allow you to directly print a stylesheet to your header.

Further reading at WordPress Developers.

  • Thank you. I'll try that then. But is this performance-wise really better than just leaving everything in the standard style.css file? Won't there be more queries, eventually slowing down the performance? I'm not a developer. I'm just trying to optimize my own theme without knowing much aboud codes. – japanworm Apr 30 '17 at 15:43
  • You're welcome. It depends. You must keep in mind, that CSS files will be cached. So, it will only take more time on the first load. Although huge CSS files will decrease the browser's performance, the same way huge HTML files do. Eventually it depends on your definition of HUGE. You can try Automtimizer, or minify your CSS in this case. – Jack Johansson Apr 30 '17 at 16:02

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.