Load a stylesheet with wp_enqueue_style and a version

Description: Add a file css/custom.css in your theme and load it with the version 2.0. Check the tag which WordPress prints in the page.

Hint:

  • Use the hook wp_enqueue_scripts and the function wp_enqueue_style().

Solution

<?php
add_action( 'wp_enqueue_scripts', function () {
	wp_enqueue_style(
		'tc-custom',
		get_template_directory_uri() . '/css/custom.css',
		array(),
		'2.0'
	);
} );
Terminal output

$ curl -s http://example.com/ | grep "tc-custom" | sed 's/^[ \t]*//'
<link rel='stylesheet' id='tc-custom-css' href='http://example.com/wp-content/themes/tc-theme/css/custom.css?ver=2.0' media='all' />

How it works

  • wp_enqueue_style() adds the stylesheet to the queue, and WordPress prints the link tag in wp_head().
  • The version 2.0 becomes ?ver=2.0. When you change the file, change the version, so the browsers load the new file.

Read Enqueue Scripts and Styles.


Learn more about the similar topics:
Tutorials
WordPress Themes
WordPress Top Theme List
WordPress Theme Files and Functions
WordPress Template Hierarchy
WordPress Enqueue Scripts and Styles
WordPress Loop
WordPress WP_Query Class
Exercises & Assignments
Build and activate a minimal classic theme
Show the three latest posts with WP_Query
Load a stylesheet with wp_enqueue_style and a version
Show a message only on the front page
Create a child theme which changes the footer
Interview Questions & Answers
What is a WordPress theme?
What are commonly used WordPress theme functions?
Which function is used to get the home URL in WordPress?
Which are the necessary files for a WordPress theme?
What is the use of the wp_head() function in WordPress?
What is the WordPress Loop?
What is the difference between is_home() and is_front_page()?