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:
your-website.com/wp-content/plugins/your-plugin/script.js
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');
file functions hook import plugin script tag stylesheet