I register and enqueue stylesheet but nothing is rendered

I’m told it’s very important to register and enqueue styles and scripts in WordPress even though it’s a real pain.

I had no problem with the scripts however when I try the styles, WordPress shows nothing in the code for stylesheets. I’d like to get in the habit of building my themes the correct way so I’d like to learn how this is done, but I can’t understand why my css is not added to the code when the scripts are added. See code to functions file below:

<?php

function alpha_scripts(){

  $script = get_template_directory_uri() . '/assets/scripts/';

  wp_register_script('bootstrap-js', $script . 'bootstrap.min.js', array('jquery'),'', false);

  //wp_enqueue_script('jquery');
  wp_enqueue_script('bootstrap-js');
}

function alpha_styles(){

  $style = get_template_directory_uri() . '/assets/styles/';

    wp_register_style('bootstrap-css', $style . 'bootstrap.min.css','','', 'screen');
    wp_register_style('alpha-css', $style . 'alpha.css','','', 'screen');

    wp_enqueue_style('bootstrap-css');
    wp_enqueue_style('alpha-css');
}

function alpha_menus() {
  register_nav_menus(
    array(
      'main-menu' => __( 'Primary Menu' ),
      'footer-menu' => __( 'Footer Menu' )
    )
  );
}

add_action('wp_enqueue_scripts', 'alpha_scripts');
add_action('wp_enqueue_styles', 'alpha_styles');
add_action('after_setup_theme', 'alpha_menus');

?>

What am I doing wrong here? I’ve tried using different references for the url, like get_template_directory_uri() and get_stylesheet_directory_uri() but as I suspected those two made no difference.

1 Answer
1

You’re doing well – just one thing you need to change, and I reckon it’s a totally reasonable mistake to make:

This:

add_action('wp_enqueue_styles', 'alpha_styles');

needs to become

add_action('wp_enqueue_scripts', 'alpha_styles');

Why scripts? Because there is no WordPress action called wp_enqueue_styles. Although the functions are named wp_register_style & wp_enqueue_style, you still need to hook them to the multi-purpose wp_enqueue_scripts action.

Yes, WP core should probably just add a second action to save this issue from occuring… 🙂

Although it can be a pain at first, once you get your head around how the enqueues work, it’ll save you a lot of time in future. There’s several benefits: dependencies can be managed easily; your scripts & styles will function across multiple headers and footers if you have them; and plugins that hook into scripts & styles (eg. to concatenate/minify them) can do their job.

Leave a Comment