📦 Never Hardcode Script Tags Again
Hardcoded <script> tags cause conflicts. wp_enqueue_script() handles dependencies, order, and conditional loading.
📝 Enqueue in functions.php
function my_theme_assets() {
// Styles
wp_enqueue_style('my-theme', get_stylesheet_uri());
wp_enqueue_style('custom', get_template_directory_uri() . '/css/custom.css', array(), '1.0.0');
// Scripts
wp_enqueue_script('my-script', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0.0', true);
// Localize script (pass PHP data to JS)
wp_localize_script('my-script', 'myAjax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('my_nonce')
));
}
add_action('wp_enqueue_scripts', 'my_theme_assets');
🎯 Conditional Loading
// Only on single post pages
if (is_single()) {
wp_enqueue_script('post-specific', '...');
}
// Only on contact page
if (is_page('contact')) {
wp_enqueue_script('google-maps', 'https://maps.googleapis.com/...');
}
// Only for logged-in users
if (is_user_logged_in()) {
wp_enqueue_script('logged-in', '...');
}
// Deregister unused scripts (performance)
wp_deregister_script('wp-embed');
wp_dequeue_style('wp-block-library');
💡 Best Practices
- Always load jQuery from WordPress (not external CDN)
- Set $in_footer = true for non-critical scripts
- Version numbers for cache busting
- Deregister scripts you don’t need (emoji, embed)
“Hardcoded jQuery CDN then loaded another. Conflicts everywhere. Enqueue system fixed dependency order. WordPress best practice non-negotiable.”
