Conditional Tags to Load Styles and Scripts in WordPress
Core points
- WordPress supports conditional loading stylesheets and scripts to ensure that these files are loaded only when needed, thereby speeding up website loading and reducing unnecessary data downloads for users.
- Styling and scripts should be loaded in accordance with the best practices recommended in WordPress.org coding standards, using standard WordPress methods can avoid incompatibility issues and ensure that the website remains efficient.
- WordPress provides
wp_enqueue_style
andwp_enqueue_script
functions, which are used to include custom stylesheets and JavaScript files, respectively. These functions ensure that WordPress finds all the required stylesheets and scripts and downloads them in the correct order. - WordPress provides conditional tags that can be used in conjunction with
if...else
statements to determine which code to apply under specific conditions. These tags can be used to ensure that specific style sheets and scripts are downloaded only when visitors visit specific pages of the website.
This article is part of a series created in collaboration with SiteGround. Thank you for supporting the partners who made SitePoint possible.
If your WordPress site only needs to use specific stylesheets or JavaScript files on a specific page or only under limited conditions, you don't need to load these files every place on the site.
This article will guide you on how to load CSS styles and scripts only if the website needs them. In this way, your website will load faster and users who do not visit pages containing additional files do not need to download unnecessary data in their browser.
Why should styles and scripts be added in WordPress?
If there is an anti-pattern in WordPress development, it is to add and
<link>
tags to the <script></script>
section of the HTML document to load the stylesheet and JavaScript files separately, and then it's done.
Running a WordPress website involves using stylesheets and JavaScript code from the software itself, many plug-ins and active themes.
This means that the theme or plugin author has no idea in advance what styles and scripts will run for a particular installation, or the order in which these resources are needed. For example, let's take the jQuery library as an example. WordPress itself can use this library to handle Ajax requests and other tasks, and it can also be used by multiple plug-ins and active themes.
If plug-in and theme authors include the stylesheets and scripts they need by adding corresponding tags directly to the HTML document, this may lead to conflicts, resources being loaded multiple times, and/or incorrect loading order.
This is why you should always load styles and scripts by following the best practices recommended in WordPress.org encoding standards:
To make everything work harmoniously, it is important for themes and plugins to load scripts and stylesheets using standard WordPress methods. This will ensure that the website remains efficient and there are no incompatibility issues.
Contains CSS and JavaScript — Theme Manual
How to use wp_enqueue_style
and wp_enqueue_script
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
- Parameter is the name of the stylesheet. You can name it main, portfolio, etc. according to the purpose of the file. If you include a stylesheet from a JavaScript plugin, just use the name of the plugin.
$handle
- represents the URL where the stylesheet resides.
$src
The - parameter specifies whether this style sheet depends on another style sheet to work properly.
$deps
- Determines the version number of the style sheet.
$ver
- represents the media types that apply to style sheets, such as all, screen, print, etc.
$media
wp_enqueue_style( 'portfolio', get_template_directory_uri() . '/css/portfolio.css',false,null,'screen');
wp_enqueue_script($handle, $src, $deps, $ver, $in_footer)
, except that the last parameter, which sets true or false values based on whether you want to place the wp_enqueue_style
or <script>
part of the document. <head>
<body>
Suppose you want to add portfolio.js to your website, the code looks like this:
This code tells WordPress:
wp_enqueue_script( 'portfolio', get_template_directory_uri() . '/js/portfolio.js', array ( 'jquery' ), null, true);
You want to use the portfolio file, which is located in the js subfolder within the active topic directory.
- WordPress requires jQuery to be downloaded before loading the portfolio.js, otherwise the latter won't work properly (you don't need to import jQuery, as it's already bundled with WordPress by default).
- WordPress requires this file to be added in the section of the HTML document.
-
<body>
You may need to include multiple stylesheets or script files, in which case, wrap all calls to
in one function, and then hook this function to the appropriate WordPress action hook up. wp_enqueue_style()
wp_enqueue_script()
This is an example. If you are developing a WordPress theme, you can add it to your functions.php file.
Now you can rest assured that WordPress will find all the required stylesheets and scripts and download them in the correct order.
function mytheme_styles_scripts() { // 主样式表,style.css wp_enqueue_style( 'style', get_stylesheet_uri() ); // 作品集部分的样式表 // (与网站的其余部分不同) wp_enqueue_style( 'portfolio', get_template_directory_uri() . '/css/portfolio.css',false,null,'screen'); // 作品集部分的 JS wp_enqueue_script( 'portfolio', get_template_directory_uri() . '/js/portfolio.js', array ( 'jquery' ), null, true); } // 将函数挂接到 wp_enqueue_scripts 操作挂钩 add_action( 'wp_enqueue_scripts', 'mytheme_styles_scripts' );
The above code works well and follows WordPress best practices. However, WordPress will download both portfolio.css and portfolio.js from every place on your website. If your visitors have never visited your portfolio page, this is unfortunate, but can happen, and the browser will load two unnecessary files.
Now, let's go a step further and make sure WordPress contains both portfolio.css and portfolio.js only if the visitors access your portfolio section.
WordPress conditional tag
WordPress provides conditional tags that are used in conjunction with the regular if...else
statements to easily choose which code to apply under specific conditions.
For example, if you want to execute some code only on the homepage of your website and other code elsewhere, you will write something like this:
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
Instead, if you want to execute certain code anywhere outside the home page of the website, you will write:
wp_enqueue_style( 'portfolio', get_template_directory_uri() . '/css/portfolio.css',false,null,'screen');
WordPress provides a large number of conditional tags, and you can view a full list in the Conditional Tags section of the theme manual.
You can use the conditional tag to ensure that WordPress downloads portfolio.css and portfolio.js only if visitors visit your website's portfolio page.
Let's check out some ways you can do this.
User Page ID
You can use the Conditional Tag to check if the user is using the portfolio page ID on the website.
To understand the page ID, do the following:
- Login to the admin panel of your WordPress website.
- Click on the page to access a list of all pages on the website.
- Click on the title of the page you are interested in and open it in the editor.
- The page is now open in the editor, please check the URL in the browser's address bar. You should see something like post= plus a number. This number is the page ID:
Now that you know the page ID, you can use the conditional tag to modify the code that previously contained the theme stylesheet and scripts, as shown below:
wp_enqueue_script($handle, $src, $deps, $ver, $in_footer)
Use page title
The page's conditional label also applies to the page title. If your portfolio page has the title "My portfolio", the code might look like this (I just added the conditional section for brevity):
wp_enqueue_script( 'portfolio', get_template_directory_uri() . '/js/portfolio.js', array ( 'jquery' ), null, true);
Use page alias
You can use the conditional tag with a page alias, which is the user-friendly URL of the page. The following is what it looks like in actual application:
function mytheme_styles_scripts() { // 主样式表,style.css wp_enqueue_style( 'style', get_stylesheet_uri() ); // 作品集部分的样式表 // (与网站的其余部分不同) wp_enqueue_style( 'portfolio', get_template_directory_uri() . '/css/portfolio.css',false,null,'screen'); // 作品集部分的 JS wp_enqueue_script( 'portfolio', get_template_directory_uri() . '/js/portfolio.js', array ( 'jquery' ), null, true); } // 将函数挂接到 wp_enqueue_scripts 操作挂钩 add_action( 'wp_enqueue_scripts', 'mytheme_styles_scripts' );
Conclusion
In this article, I discuss how to include stylesheets and script files in a conditional manner in a WordPress website. In some cases, the number of extra styles is small, so it doesn't make much sense to create a dedicated style sheet for them. This will only generate an HTTP request that your website may not need.
However, under appropriate conditions, for example, the design of a page or theme area is different from the rest of the website, the selective loading of style sheets and scripts follows WordPress best practices and ensures that the visitor's browser only downloads Displays the amount of data required for the required content.
How do you include custom scripts and styles into your WordPress site? Click the comment box below to share.
FAQs (FAQ) about conditional tags and loading styles and scripts in WordPress
What are the conditional tags in WordPress and how do they work?
The conditional tag in WordPress is a PHP function used in the theme file to change the content displayed on a specific page based on the conditions that the page satisfies. They are used to determine whether a specific condition is met before executing a specific function. For example, you can use the Conditional Tag to check if a page is a single post before displaying a specific sidebar.
How to use conditional tags to load styles and scripts in WordPress?
To use conditional tags to load styles and scripts in WordPress, you need to add your scripts and styles in the theme's functions.php file. You can use the wp_enqueue_script
and wp_enqueue_style
functions with the conditional tags. For example, if you want to load scripts only on the home page, you can use the is_home()
conditional tag.
What are some common conditional tags in WordPress?
Some commonly used condition tags in WordPress include is_single()
, is_page()
, is_home()
, is_front_page()
, is_category()
, is_tag()
, is_author()
,
How to create conditional code snippets in WordPress?
if
To create a conditional code snippet in WordPress, you need to use the conditional tag in the PHP if
statement. The code in the if
statement will be executed only when the condition is met. For example, to display code snippets only on the home page, you can use the is_home()
conditional tag in the
Why is my style not loading in WordPress?
wp_enqueue_style
If your style is not loading in WordPress, it may be due to a number of reasons. The most common reason is that the style files are not registered correctly in the functions.php file. Make sure you have used the
How to load conditional CSS in WordPress the correct way?
wp_enqueue_style
To load conditional CSS in WordPress, you need to use the is_home()
function to register the CSS file in the theme's functions.php file. You can use the Conditions tab to specify the conditions on which the CSS file should be loaded. For example, to load CSS files only on the home page, you can use the
Can I use multiple conditional tags in WordPress?
Yes, you can use multiple conditional tags in WordPress. You can combine them using logical operators such as AND(&&) and OR(||). For example, to check if a page is a single post and is not a home page, you can use the is_single()
and the !is_home()
conditional tags.
How to use the conditional tag to load different styles for different pages in WordPress?
To load different styles for different pages in WordPress, you can use the conditional tags in the theme's functions.php file. For each style, use the wp_enqueue_style
function and check the conditional tags for a specific page. For example, to load a specific style for the home page and to load a different style for a single post, you can use the is_home()
and is_single()
conditional tags.
and is_home()
in WordPress? is_front_page()
The Conditional tag in WordPress checks if the home page is being displayed, while the is_home()
Conditional tag checks if the home page is being displayed. If you have set your homepage to show your latest posts, both tags will return true. However, if you have set the static page as home page, is_front_page()
will return true for this page, and is_front_page()
will return true for the page that is set as the post page. is_home()
Yes, you can use conditional tags outside of looping in WordPress. However, some conditional tags (such as
and is_single()
) may not work as expected when used before the loop. This is because WordPress only knows the details of the query after the loop begins. Therefore, it is generally recommended to use these conditional labels within or after the loop starts. is_page()
The above is the detailed content of Conditional Tags to Load Styles and Scripts in WordPress. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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

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.

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

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

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.

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin
