Categories
guides

Creating a WordPress Child Theme, and Importing CSS, JS, and CDN through Functions.php

Introduction

This is a short reference guide on making child themes and preparing them for development. I will come back to this guide and fill in some additional details.

Create a Location for your Child Theme

Go to the following…

  • Add an Assets Folder
  • Add the theme’s stylesheet
    • file name: style.css

Every wordpress theme need this style.css file, and they need to begin with at least 2 specific comments. These comments are parsed by wordpress and used during installation.

A few other comments are also useful, but not necessary.

to the location:

assets/css
  • … and amy javascript files

I am going to need to use some javascript for this site, so i’ll be adding a file called mkd-index.js to the location:

assets/js

Create & Import Everything in The Fuctions.php File

In the theme root, you should create a file called functions.php. We will add the following code:

<?php 

// CSS
// Include parent and child theme style sheets
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
    $parenthandle = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
    $theme = wp_get_theme();
    wp_enqueue_style( $parenthandle, get_template_directory_uri() . '/style.css', 
        array(),  // if the parent theme code has a dependency, copy it to here
        $theme->parent()->get('Version')
    );
    wp_enqueue_style( 'child-style', get_stylesheet_uri(),
        array( $parenthandle ),
        $theme->get('Version') // this only works if you have Version in the style header
    );
}

// JavaScript
function collectiveray_load_js_script() {
	if( is_page( 2 ) ) {
	$parenthandle = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
	$theme = wp_get_theme();
	  //wp_enqueue_script('mkd-index', '/assets/js/mkd-index.js', array('jquery'), '', false);
	  //or use the version below if you know exactly where the file is
	  wp_enqueue_script( 'mkd-index.js', get_stylesheet_directory_uri() . '/assets/js/mkd-index.js');
	}
  }
  
  add_action('wp_enqueue_scripts', 'collectiveray_load_js_script'); 

  // CDN 
  wp_register_script( 'GSAP', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.6/gsap.min.js', null, null, true );
  wp_enqueue_script('GSAP');

Breaking Down the Enqueue Code

I want to make sure to keep all my child theme’s modifications actually within my child theme, so our functions.php file should start from the child theme’s root.

If you look at this WordPress example on how to include CSS and JS files (here and here), the code included will default to the parent theme’s root directory. In the second example, it’s a bit confusing because the code is filed under Advanced Topics > Child Themes.

So, we’re going to use a different function to get the path of the child theme’s directory. We’ll be using:

 get_stylesheet_directory_uri()