In WordPress, wp_enqueue_style()
is a function that’s used to add CSS stylesheets to your WordPress theme. This is an integral part of WordPress theme development and should be used whenever you want to add a new CSS file to your theme.
Here’s how you can use it:
-
Create your CSS file
First, you need to create a CSS file that you want to add to your theme. You can name it anything you like. For this example, let’s name it
custom-style.css
. -
Place the CSS file in your theme directory
Once your CSS file is ready, place it in your theme directory. For instance, if you’re creating a child theme, you might put it in the
wp-content/themes/your-child-theme/
directory. -
Prepare to enqueue the style
Now you need to add the necessary PHP code to your theme’s
functions.php
file to tell WordPress to load your new stylesheet. You’ll do this by using thewp_enqueue_style()
function. -
Add
wp_enqueue_style()
tofunctions.php
Open your theme’s
functions.php
file, then add the following code:function my_custom_styles() { wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/custom-style.css' ); } add_action( 'wp_enqueue_scripts', 'my_custom_styles' );
In the
wp_enqueue_style()
function:-
The first parameter
'custom-style'
is the name you’re giving to your style. This name is used as a handle and should be unique. -
The second parameter is the path to your CSS file.
get_stylesheet_directory_uri()
is a WordPress function that gets the URI of the current theme directory.
The
add_action()
function tells WordPress to run yourmy_custom_styles()
function when it’s time to enqueue scripts and styles. -
-
Test your new style
Once you’ve added the code to your
functions.php
file and saved it, you can start using your new styles in your theme. If you added a rule in yourcustom-style.css
file, you should see it taking effect on your website.
Always remember to enqueue your styles rather than directly linking to them in your header, as enqueuing ensures that styles load in the correct order and that they don’t conflict with plugins and other themes.