sitespecificplugin

Create a Simple Plugin in WordPress – 4 – how to add custom js & css file into plugin

There is a simple function called wp_enqueue_script & wp_enqueue_style to add js & css but the arguments we are passing in both functions are important.

To add js we use, wp_enqueue_script(arg1, arg32, arg3, arg4, arg5)

where,
arg1 = handler that is the id of the js file, unique id
arg2 = JS file location
arg3 = Dependent JS files if any
arg4 = file version, to make it unique always we use file modification time
arg5 = weather we need to add this js in footer or not. true means add in footer.

To add style we use wp_enqueue_style which is having almost same type of arguments like id/handler, file-path, dependency, version & media(all by default)

here is the code. we can’t simply add this lines to plugin file but we use hook to add these custom script at time of event when scripts are adding into WordPress itself. so we use add_action(‘wp_enqueue_scripts’, ‘my_custom_script’);

Here is the code with simple style css and a js having console.log code.

function my_custom_script()
{
    $script_path = plugins_url('js/main.js', __FILE__);
    $js_version = filemtime(plugin_dir_path(__FILE__) . '/js/main.js');
    // echo $js_version;
    wp_enqueue_script('userinfo-js', $script_path, array(), $js_version, true);

    $style_path = plugins_url('css/style.css', __FILE__);
    // echo $style_path;
    wp_enqueue_style('userinfo-style', $style_path);
}
add_action('wp_enqueue_scripts', 'my_custom_script');

That’s it for now.