When developing a WordPress theme or a WordPress plugin in most case we want to add our own CSS and JavaScript files to it.

Luckily in WordPress there is an easy way to include CSS or JavaScript resources to your project, it slightly differs between a theme and a plugin, we will describe them both in this article.

Theme

In order to include CSS and JavaScript in our custom theme, we need to add them in the file functions.php of the theme.

Adding CSS files into our theme requires to register and enqueue the style. Multiple CSS files can be added by duplicating the wp_register_style and wp_enqueue_style functions.

The example below adds /assets/css/style.css from within the theme folder to the page.

function theme_css()
{
   wp_register_style('theme-css', get_template_directory_uri() . '/assets/css/style.css', false,'1.1','all');
   wp_enqueue_style('theme-css');
}
add_action('wp_enqueue_scripts', 'theme_css');

Adding JavaScript has a similar approach except that instead of register and enqueue style we use script.
The example below will add /assets/js/custom.js from within the theme folder to the page.

function theme_js()
{
    wp_register_script('theme-js', get_template_directory_uri() . '/assets/js/custom.js', [], 1.1, true);
    wp_enqueue_script('theme-js');
}
add_action('wp_enqueue_scripts', 'theme_js');

Plugin

For a plugin there is a slight different approach, in the plugin file adding a CSS resource can do as following.

function plugin_css_init() {
    wp_register_style('plugin-css', plugins_url('css/plugin.css',__FILE__), false, 1.1, 'all');
    wp_enqueue_style('plugin-css');
}
add_action('wp_enqueue_scripts','plugin_css_init');

This example adds /css/plugin.css in the plugin folder to the page, this however is only for the pages on the public side. If you want to add a CSS file to the WordPress admin panel the add_action needs to change:

add_action('admin_enqueue_scripts','plugin_css_init');

For adding JavaScript it is more or less the same. The following example adds /js/plugin.js in the plugin folder to the page.

function plugin_js_init() {
    wp_register_script('plugin-js', plugins_url('js/plugin.js',__FILE__), [], 1.1, true);
    wp_enqueue_script('plugin-js');
}
add_action('wp_enqueue_scripts','plugin_js_init');

Also for JavaScript the procedure to add files to the WordPress Admin panel is slightly different and the add_action needs to change:

add_action('admin_enqueue_scripts','plugin_js_init');

With this information it should be easy to add CSS or JavaScript resources to the WordPress page or WordPress admin panel.