YogeshChauhan . com

How to include CSS and JavaScript files in your WordPress plugin?

in WordPress on June 10, 2021

When you’re developing a WordPress plugin or theme, you would probably want to make it look pretty using CSS and add some JavaScript or maybe you just want to import some fonts using a third party URL.

For all those things mentioned above we need to determine both, the plugin and content directories.

WordPress has tons of hooks and functions readily available for almost everything, almost! We can make use of those functions to achieve our goal of importing the CSS and JS files.

Use the WordPress functions to find a directory path rather than hard coding an absolute path to the wp-content directory as WordPress allows you to put your themes, plugins, uploads folders anywhere you’d like.

__FILE__ constant

PHP has a great constant, __FILE__, that resolves symlinks automatically.

So, if your plugins folder is symlinked then your hard coded JavaScript or CSS files path won’t work properly.

How to load files?

You can just

You can use plugins_url() function to include CSS, JavaScript or other external files. Just like this:

plugins_url( 'script.js', _FILE_ );

The code above will return the following path:


How to load plugin scripts to frontend page?

You can use the same functions that you use to load your theme CSS and JavaScript files to load the plugin script files into the frontend page.

To load CSS files you can use wp_enqueue_style() and to load JavaScript files you can use wp_enqueue_script() function. In both cases, you’ll pass the file URL using plugins_url().

Just like this:

function yc_load_scripts($hook) {     
  wp_enqueue_script( 'script-js', plugins_url( 'js/script.js', __FILE__ ), array(), '1.0.0' );
  wp_register_style( 'style',    plugins_url( 'style.css',    __FILE__ ), false,   '1.0.0' );
add_action('wp_enqueue_scripts', 'yc_load_scripts');


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

A quick introduction to API, REST API and PostmanMiscSolution to “TypeError: ‘x’ is not iterable” in Angular 9AngularWhat Does Host-Based Intrusion Detection System (HIDS) Mean and What Are Some Advantages Over NIDS?MiscList of all Pseudo Elements in CSSCSSUPDATE and DELETE Statements in PostgresPostgresAttributes and Properties in JavaScript and HTMLHTML