Monday, June 29, 2015

Adding in Third-Party CSS and JavaScript Libraries

Because we are going to want to use third-party CSS and JavaScript libraries, we need to learn how to accomplish this in Wordpress.

As an example, we are going to load the Bootstrap library: http://getbootstrap.com/. The first step is to get the files into the template folder, e.g., wp-content/themes/barbones.  In my case, I used a tool called bower to get the files downloaded: http://bower.io/.

We do this by simply updating index.php as follows:

index.php
<html>
  <head>
    <title>Barebones</title>
    <link rel="stylesheet" href="<?php echo bloginfo("template_url"); ?>/bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
  </head>
  <body>
    <?php while (have_posts()) : the_post(); ?>
      <?php the_content(); ?>
    <?php endwhile; ?>
    <script src="<?php echo bloginfo("template_url"); ?>/bower_components/jquery/dist/jquery.min.js"></script>
    <script src="<?php echo bloginfo("template_url"); ?>/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
  </body>
</html>

note: The locations of one's bootstrap files will differ depending on how one download them.

A Better Way

While the above method is super clean, it does not play well with Wordpress and other plugins, e.g., any JavaScript or CSS that they need will not be inserted.  The most obvious example of this is the lack of the WordPress toolbar when logged in.

The proper way then involves registration and enqueueing both JavaScript and CSS resources; e.g., the following explains script registration: https://codex.wordpress.org/Function_Reference/wp_register_script.

The first step is to create and update the functions.php file with the following as the example of using bootstrap:

functions.php
<?php
  function add_theme_scripts() {
    wp_register_style('bootstrap',
      get_template_directory_uri() .
      '/bower_components/bootstrap/dist/css/bootstrap.min.css',
      array(), '20150629', 'all');
    wp_register_style('style', get_stylesheet_uri(),
      array(), '20150629', 'all');
    wp_register_script('bootstrap',
      get_template_directory_uri() .
      '/bower_components/bootstrap/dist/js/bootstrap.min.js',
      array('jquery'), '20150629', true);
    wp_enqueue_style('bootstrap');
    wp_enqueue_style('style');
    wp_enqueue_script('bootstrap');
  }
  add_action('wp_enqueue_scripts', 'add_theme_scripts');
// REMOVED CLOSING TAG PER WP CODING STANDARDS

note: As to removing the closing tag: https://make.wordpress.org/core/handbook/coding-standards/php/#remove-trailing-spaces.

Then we need to update index.php as follows:

index.php
<html>
  <head>
    <title>Barebones</title>
    <?php wp_head() ?>
  </head>
  <body>
    <?php while (have_posts()) : the_post(); ?>
      <?php the_content(); ?>
    <?php endwhile; ?>
    <?php wp_footer() ?>
  </body>
</html>

No comments:

Post a Comment