Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it better to use wp_enqueue_style than the link tag in WordPress?

Tags:

wordpress

I am pretty new to WordPress development. I read that it's better to use wp_enqueue_style and do_action inside the functions.php file rather than linking CSS files directly as I would when not using WordPress.

Why this is a best practice? What are its advantages?

like image 554
Kareem Abdelwahed Avatar asked Oct 24 '25 19:10

Kareem Abdelwahed


1 Answers

If you have activated child theme then use get_template_directory_uri() functions.

If you have activated parent theme then use get_stylesheet_directory_uri() functions.


get_template_directory_uri will always refer to the parent theme folder for assets.

get_stylesheet_directory_uri will refer to the "current" theme folder for assets (which could be the parent or the child, depending on where it is called).

Child theme example:

wp_enqueue_style( 'my_child_styles', get_stylesheet_directory_uri().'/style.css' );

Parent theme Example

wp_enqueue_style( 'my_parent_styles', get_template_directory_uri().'/style.css' );

Method-1

// load css into the website's front-end
function mytheme_enqueue_style() {
    wp_enqueue_style( 'mytheme-style', get_stylesheet_directory_uri().'/style.css' ); 
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' );

Method-2

// Add this code in your functions.php
function add_stylesheet_to_head() {
      echo "<link href='".get_stylesheet_directory_uri()."/style.css' rel='stylesheet' type='text/css'>";
}

add_action( 'wp_head', 'add_stylesheet_to_head' );
like image 102
Purvik Dhorajiya Avatar answered Oct 28 '25 02:10

Purvik Dhorajiya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!