Adding custom code into header.php using a plugin

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.

Leave a Comment

error code: 523