Create Custom Menu in WordPress Dashboard
Complete tutorial on create custom menu in wordpress dashboard. Discover practical examples, implementation tips, and expert advice for WordPress and WooCo
Read More โAdd CSS and JavaScript files correctly in WordPress using wp_enqueue_scripts action hook, wp_enqueue_script, and wp_enqueue_style functions. Prevent conflicts by properly declaring dependencies like jQuery, load assets conditionally, optimize performance by loading scripts in footer, and follow WordPress best practices for theme and plugin development. Ensures compatibility, avoids duplicate loading, and maintains clean code structure.
Adding custom CSS and JS files in WordPress should always be done using the wp_enqueue_scripts hook. This method ensures your styles and scripts are integrated smoothly and won’t break your theme or other plugins.
Why Use wp_enqueue_scripts?
Instead of directly placing styles or scripts into your template files, this hook helps you:
The functions wp_enqueue_script() and wp_enqueue_style() make sure everything loads correctly in the document head or footer.
Sample: Enqueuing Scripts and Styles
Add this code to your theme’s functions.php file:
function custom_enqueue_assets() {
wp_enqueue_script('site-script', get_template_directory_uri() . '/js/site-script.js', array('jquery'), '1.0', true);
wp_enqueue_style('site-style', get_template_directory_uri() . '/css/site-style.css', array(), '1.0');
}
add_action('wp_enqueue_scripts', 'custom_enqueue_assets');
Explanation
wp_enqueue_script includes your JS file and sets jQuery as a dependency.wp_enqueue_style adds your CSS without any dependencies.Ensure your file paths match your theme’s structure. This best practice method ensures that your site stays clean and compatible.
Conclusion
Follow this approach to add scripts and styles properly in WordPress. It ensures better performance, fewer bugs, and cleaner theme development. Refer to the WordPress Codex for advanced details.
Search our archives or reach out to our team for solutions and expert advice.