Table of Contents
Key Takeaways
Enqueuing Scripts and Styles
Remove Unnecessary Scripts
Working with Shortcodes
Conclusion
Frequently Asked Questions (FAQs) about Enqueuing Scripts and Styles in WordPress
What is the purpose of enqueuing scripts and styles in WordPress?
How do I enqueue a script in WordPress?
What is the difference between wp_enqueue_script() and wp_register_script()?
Can I enqueue styles in WordPress?
What is the ‘wp_enqueue_scripts’ action hook?
Why is it important to specify dependencies when enqueuing scripts or styles?
How can I dequeue a script or style in WordPress?
Can I enqueue scripts and styles in the admin area?
What is the ‘wp_print_scripts’ action hook?
Can I enqueue scripts and styles conditionally?
Home CMS Tutorial WordPress Enqueuing Scripts and Styles in WordPress

Enqueuing Scripts and Styles in WordPress

Feb 15, 2025 pm 01:18 PM

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="<?= plugins_url('assets/js/main.js') ?>"></script>
Copy after login
Copy after login

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'] );
} );
Copy after login
Copy after login

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'] );
} );
Copy after login
Copy after login

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'] );
    }
} );
Copy after login
Copy after login

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="<?= plugins_url('assets/js/main.js') ?>"></script>
Copy after login
Copy after login

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'] );
} );
Copy after login
Copy after login

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'] );
} );
Copy after login
Copy after login

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'] );
    }
} );
Copy after login
Copy after login

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
} );
Copy after login

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 of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How much does WordPress cost? How much does WordPress cost? Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

See all articles