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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.