3

I have several different pages. Every one of them has different css links. Rather than the css links all items are same in the head element of those pages. I need to shift those head element to header.php so that I can include head using get_header().

So How can I load different css file for different pages? I have around 20 different pages, so load file after condition check is bit messy to me.
Is there any better approach to do than this?
If possible suggest me to solve this problem using custom plugin?

page 1:

<html lang="en">
<head>
     <link rel="stylesheet" href="css/one.css" />
     .......
 </head>

page 2:

<html lang="en">
<head>
     <link rel="stylesheet" href="css/two.css" />
     .......
 </head>
1
  • 1
    Did you test if this really is benficial? I would presume combining them and having the file in cache would be faster than requesting 20 different files
    – kero
    Commented Jan 8, 2018 at 12:46

3 Answers 3

4

You can achieve this using conditionals inside the function enqueuing your styles.

function wpdocs_theme_name_scripts() {
    wp_enqueue_style( 'global', get_stylesheet_uri() );

    if ( is_page(5) ) {
      wp_enqueue_style( 'page-five', get_stylesheet_uri() . '/page-five-styles.css' );
    }
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

If you wanted more control over both the markup of your page and the CSS files you load, you could use WordPress' template hierarchy and create a page template or something more specific like page-5.php. Calling wp_enqueue_scripts from within these template files only loads the assets for those pages.

1

If you wish to do it in your template you can do the following.

You can learn more about the is_page function here: https://developer.wordpress.org/reference/functions/is_page/

<html lang="en">
<head>
     <?php if ( is_page(1) ): //Change this number to id of page ?> 
     <link rel="stylesheet" href="css/one.css" />
     <?php endif; if ( is_page(2) ): //Change this number to id of page ?>
     <link rel="stylesheet" href="css/two.css" />
     <?php endif; ?>
 .......
</head>
0
<html lang="en">
    <head>
<?php global $post;
if( $post->ID == 346) { ?>
       <link rel="stylesheet" href="css/one.css" />
<?php } ?>
    elseif ( $post->ID == 342){ ?> 
         <link rel="stylesheet" href="css/two.css" />
         <?php } else{ //Change this number to id of page ?>
         <link rel="stylesheet" href="css/three.css" />
         <?php } ?>
     .......
    </head>

Your Answer

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

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