How to include CSS and Javascript files in WordPress Plugin
To include JavaScript and CSS files in WordPress, you can use the wp_enqueue_script() and wp_enqueue_style() functions, respectively. These functions ensure that the files are properly loaded and managed by WordPress. Here’s how you can include JavaScript and CSS files in WordPress:
1. Include JavaScript files:
Place the following code in your plugin file:
function custom_plugin_enqueue_scripts() { wp_enqueue_script('custom-script-handle', plugins_url('public/js/custom-js.js', __FILE__), array('jquery'), '1.0.0', true); wp_enqueue_style('custom-style-handle', plugins_url('public/css/custom-style.css', __FILE__), array(), '1.0.0', 'all'); } add_action('wp_enqueue_scripts', 'custom_plugin_enqueue_scripts');
Here I have created a public folder to manage directories of admin and frontend separately.
Remember to adjust the file paths
‘public/js/custom-js.js’
‘public/css/custom-style.css’
to the actual paths relative to your plugin or theme. Place your JavaScript and CSS files in the corresponding directories.