search
HomeCMS TutorialWordPressEnqueuing Scripts and Styles in WordPress

Enqueuing Scripts and Styles in WordPress

Key Takeaways

  • Enqueuing scripts and styles in WordPress is essential for maintaining performance and preventing conflicts between different scripts and styles. The recommended way to add scripts is using the admin_enqueue_scripts hook, prefixing the handler to avoid conflicts and ensure the script is always loaded.
  • It is possible to remove unnecessary scripts that are causing errors or conflicts by using the wp_deregister_style function. This is particularly useful in debug mode when troubleshooting issues.
  • Working with shortcodes often requires scripts to be injected into the page. This can be achieved by registering a callback on the_content filter and testing if it contains the shortcode. However, this solution can have performance issues on high load websites. A more sophisticated solution involves using Composer to load classes and registering the shortcode inside the post content.

After developing WordPress plugins and themes for a while, you start thinking more and more about your theme performance and what problems could it cause for your customers. One of these problems is enqueuing scripts and styles. In this article we’ll cover the basics of enqueuing scripts and best practices for different use cases. You can check this article for a beginner overview on managing your WordPress assets.

Enqueuing Scripts and Styles in WordPress

Enqueuing Scripts and Styles

If you need some CSS or JavaScript code to be injected into certain pages of your website, we tend to either add them inside the same markup file or add them using a direct URL to the file.

// ...
<script type="text/javascript">
    // some JS code
</script>

<style type="text/css">
    // some CSS code
</style>
//...

<script type="text/javascript" src="<?=%20plugins_url('assets/js/main.js')%20?>"></script>

However, this is not the recommended way for adding scripts, and caching plugins won’t optimize and cache your assets to increase website performance. We need to use the admin_enqueue_scripts hook.

add_action( 'admin_enqueue_scripts', function($hook) {
    $pluginPrefix = "my-prefix";
    wp_enqueue_script( "{$pluginPrefix}main-js", plugins_url('assets/js/main.js'), ['jquery'] );
} );

The first parameter for the wp_enqueue_script method is the script handler name, we should always prefix the handler to avoid any conflicts and make sure that our script will always be loaded.

The current solution isn’t perfect, and our script is included in every back end page. We can use the $hook variable passed to the callback function to test for a certain page.

add_action( 'admin_enqueue_scripts', function($hook) {
    if ( !in_array($hook, array("options-general.php", "post-new.php")) )
        return;

    $pluginPrefix = "my-prefix";
    wp_enqueue_script( "{$pluginPrefix}main-js", plugins_url('assets/js/main.js'), ['jquery'] );
} );

Now, our script will only be included inside the settings and new post pages. We can go further to only include our styles when the user is creating a new page.

add_action( 'admin_enqueue_scripts', function($hook) {
    if ( $hook == "post-new.php" && isset($_GET['post_type']) && $_GET['post_type'] == "page" )
    {
        $pluginPrefix = "my-prefix";
        wp_enqueue_script( "{$pluginPrefix}main-js", plugins_url('assets/js/main.js'), ['jquery'] );
    }
} );

Remove Unnecessary Scripts

Most developers don’t care about enqueuing their scripts just when needed, this is why we’ll always end up getting unexpected errors and weird styling issues. When noticing that a script is throwing an error or causing conflicts, you can remove it before adding your own, this is often useful in debug mode.

// ...
<script type="text/javascript">
    // some JS code
</script>

<style type="text/css">
    // some CSS code
</style>
//...

<script type="text/javascript" src="<?=%20plugins_url('assets/js/main.js')%20?>"></script>

Working with Shortcodes

Most plugins and themes provide a set of shortcodes to interact with the website, sometimes they need to inject scripts into the page. Sadly, we cannot test for front end pages as we did previously for the back end.

An easy way to achieve this is to register a callback on the_content filter and test if it contains your shortcode. If it returns yes, you can enqueue your scripts, otherwise do nothing.

add_action( 'admin_enqueue_scripts', function($hook) {
    $pluginPrefix = "my-prefix";
    wp_enqueue_script( "{$pluginPrefix}main-js", plugins_url('assets/js/main.js'), ['jquery'] );
} );

The above code works great, and will only enqueue our scripts for posts containing our shortcode. However, this solution has some serious performance issues on high load websites. We’ll create a more sophisticated solution for this problem.

If you’re not already using Composer to load your classes, I advise you to start doing so. Our plugin composer.json file would look like the following:

add_action( 'admin_enqueue_scripts', function($hook) {
    if ( !in_array($hook, array("options-general.php", "post-new.php")) )
        return;

    $pluginPrefix = "my-prefix";
    wp_enqueue_script( "{$pluginPrefix}main-js", plugins_url('assets/js/main.js'), ['jquery'] );
} );

The src/shortcodes/HelloShortcode.php class holds our shortcode definition.

add_action( 'admin_enqueue_scripts', function($hook) {
    if ( $hook == "post-new.php" && isset($_GET['post_type']) && $_GET['post_type'] == "page" )
    {
        $pluginPrefix = "my-prefix";
        wp_enqueue_script( "{$pluginPrefix}main-js", plugins_url('assets/js/main.js'), ['jquery'] );
    }
} );

The run method will return the HTML markup for our shortcode, and will set the loaded static attribute to true when the shortcode is used.

The enqueueScripts method will enqueue our styles when the plugin is loaded. The remaining part will register our shortcode to be recognized inside the post content.

add_action( 'admin_enqueue_scripts', function($hook) {
    $unautorized_styles = [
        'script1',
        'another-script'
    ];

    foreach ( $unautorized_styles as $handle )
    {
        wp_deregister_style( $handle );
    }

    // enqueue my scripts
} );

Surely we can avoid putting this code inside the main plugin file, but we’re going to keep things simple and readable.

The $shortcodes variable holds a list of available shortcodes. The first loop will register our shortcode and make the run method the handler. Next, we’ll use the wp_footer hook to enqueue our shortcode scripts before closing the body tag.

You can now create a new page containing our shortcode and check if our script is loaded properly.

Conclusion

This short article was a summary on how to enqueue your plugin and theme scripts, and the best way to avoid loading them inside every page on your website. If you have any question or comments, please post them below and I’ll do my best to answer them!

Frequently Asked Questions (FAQs) about Enqueuing Scripts and Styles in WordPress

What is the purpose of enqueuing scripts and styles in WordPress?

Enqueuing scripts and styles in WordPress is a best practice that ensures the correct loading order of your scripts and stylesheets. It helps to prevent conflicts between different scripts and styles that your theme or plugins may be using. By enqueuing, you’re telling WordPress when to load the script/style, where to load it, and what other scripts/styles it depends on.

How do I enqueue a script in WordPress?

To enqueue a script in WordPress, you need to use the wp_enqueue_script() function. This function requires at least two parameters: the handle (a unique name for the script) and the src (the URL of the script). You can also specify additional parameters like dependencies, version, and whether to load the script in the footer.

What is the difference between wp_enqueue_script() and wp_register_script()?

Both functions are used to register a script with WordPress, but there’s a key difference. wp_register_script() only registers the script and doesn’t enqueue it. This means the script won’t be printed unless it’s later enqueued with wp_enqueue_script(). On the other hand, wp_enqueue_script() registers and enqueues the script, meaning it will be printed in the HTML.

Can I enqueue styles in WordPress?

Yes, you can enqueue styles in WordPress using the wp_enqueue_style() function. This function works similarly to wp_enqueue_script(), but it’s used for stylesheets instead of scripts.

What is the ‘wp_enqueue_scripts’ action hook?

The ‘wp_enqueue_scripts’ action hook is where you should enqueue your scripts and styles. This hook is called when WordPress is about to print the scripts and styles in the HTML. By hooking into it, you ensure that your scripts and styles are enqueued at the right time.

Why is it important to specify dependencies when enqueuing scripts or styles?

Specifying dependencies ensures that your scripts or styles are loaded in the correct order. If your script depends on another script (like jQuery), WordPress will make sure that jQuery is loaded before your script.

How can I dequeue a script or style in WordPress?

You can dequeue a script or style in WordPress using the wp_dequeue_script() or wp_dequeue_style() function. This is useful if you want to stop a script or style from being loaded.

Can I enqueue scripts and styles in the admin area?

Yes, you can enqueue scripts and styles in the admin area using the ‘admin_enqueue_scripts’ action hook. This works similarly to the ‘wp_enqueue_scripts’ hook, but it’s used for the admin area instead of the front-end.

What is the ‘wp_print_scripts’ action hook?

The ‘wp_print_scripts’ action hook is an older hook that was used to enqueue scripts. However, it’s not recommended to use this hook anymore, as it can lead to issues with script loading order. You should use the ‘wp_enqueue_scripts’ hook instead.

Can I enqueue scripts and styles conditionally?

Yes, you can enqueue scripts and styles conditionally. For example, you can use the is_page() function to only enqueue a script or style if a certain page is being viewed. This can be useful for performance, as it prevents unnecessary scripts and styles from being loaded.

The above is the detailed content of Enqueuing Scripts and Styles in WordPress. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does WordPress's plugin ecosystem enhance its CMS capabilities?How does WordPress's plugin ecosystem enhance its CMS capabilities?May 14, 2025 am 12:20 AM

WordPresspluginssignificantlyenhanceitsCMScapabilitiesbyofferingcustomizationandfunctionality.1)Over50,000pluginsallowuserstotailortheirsiteforSEO,e-commerce,andsecurity.2)Pluginscanextendcorefeatures,likeaddingcustomposttypes.3)However,theycancausec

Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools