What's the proper way to enqueue scripts and styles in WordPress?
Answer: Follow WordPress best practices:
// Add to functions.php or your custom plugin
function theme_enqueue_scripts() {
// Enqueue CSS
wp_enqueue_style(
'main-style',
get_template_directory_uri() . '/assets/css/main.css',
array(), // dependencies
'1.0.0' // version
);
// Enqueue JavaScript
wp_enqueue_script(
'main-script',
get_template_directory_uri() . '/assets/js/main.js',
array('jquery'), // dependencies
'1.0.0', // version
true // load in footer
);
// Localize script with data
wp_localize_script(
'main-script',
'siteData',
array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'siteUrl' => site_url()
)
);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
Key points:
-
Always use wp_enqueue hooks, never hardcode script tags
-
Load scripts in footer when possible
-
Use dependencies array to manage load order
-
Include version strings for cache busting
-
Use wp_localize_script for passing PHP data to JavaScript