Adding custom stylesheet into header.php using a plugin

I have a bunch of code that I tend to put into the header.php of every site I do which are specific to Internet Explorer.

I was wondering if there was a way to insert code into a ‘standard’ header.php.

Read More

Yes, I can simply modify the header. But the idea is to make this a plugin which is generic.

Specifically, I’d like to create a plugin to echo the following in the header immediately after the default stylesheet:

<!--[if IE]>
  <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/ie.css" type="text/css" />
<![endif]-->

Related posts

Leave a Reply

2 comments

  1. Specifically, I’d like to create a plugin to echo the following in the
    header immediately after the default stylesheet

    The preferred way is to enqueue it, with the default/main stylesheet as the dependency.

    Here’s a demo plugin, with the structure:

    + plugins/
    |
    +--+ my-ie-style/
       |    
       +--+ my-ie-style.php
       |
       +--+ css/
          |
          +--+ ie.css
    

    where the my-ie-style.php file is:

    <?php
    /**
     * Plugin Name: Demo - My IE style
     * Plugin URI:  http://wordpress.stackexchange.com/a/85496/26350
     * Description: Enqueue With IE conditional, depending on the main-style stylesheet
     * Author:      wpse
     * Version:     1.0.0
     */
    add_action( 'wp_enqueue_scripts', function()
    {
        // Register
        wp_register_style( 
           'my-ie-style',                                 // handle
           plugin_dir_url( __FILE__  ) . 'css/ie.css',    // file
           [ 'main-style' ],                              // dependency    <-- ADJUST THIS!
           '1.0.0',                                       // version
           'all'                                          // media
        );
    
        // Enqueue
        wp_enqueue_style( 'my-ie-style' );
    
        // Add IE conditional
        wp_style_add_data( 
            'my-ie-style',  // handle
            'conditional',  // key ('conditional', 'rtl', 'suffix', 'after', 'alt', 'title')
            'IE'            // value
        );
    } );
    

    This will generate the following within the <head> tag:

    <link rel='stylesheet' 
          id='main-style-css'  
          href='http://example.tld/wp-content/themes/mytheme/style.css?ver=4.5.3' 
          type='text/css' 
          media='all' />
    
    <!--[if IE]>
    <link rel='stylesheet' 
          id='my-ie-style-css' 
          href='http://example.tld/wp-content/plugins/my-ie-style/css/ie.css?ver=1.0.0' 
          type='text/css' 
          media='all' />
    <![endif]-->
    

    where our custom IE stylesheet loads after the main stylesheet.

    Hopefully you can adjust it to your needs.