Wp enqueue style functions php

How to correctly enqueue stylesheets and script files in WordPress

For many years, the way I linked to external stylesheets in WordPress was incorrect. In this post I show you how to correctly enqueue stylesheets and script files in WordPress.

For many years, the way I linked to external stylesheets in WordPress was incorrect.

When you learn about CSS and external stylesheets you are taught to link to them using a link tag like this:

However, in WordPress, the correct way to link to stylesheets is to enqueue them within the functions.php file of your theme. The same applies to script files such as .js files.

If you aren’t familiar with the term “enqueue” it basically means to add data that is awaiting processing into a queue. So with our stylesheets and script files in WordPress, we are adding them to a queue and waiting for the correct moment to use them.

I know this might sound complicated and it certainly confused me at first, but it will become second nature to you soon.

In this post, I’ll show you how to correctly enqueue stylesheets and script files in WordPress.

How to enqueue the main style.css stylesheet

Firstly, let’s look at how to enqueue the main stylesheet of a WordPress theme: style.css.

Читайте также:  Fileoutputstream java save file

We will begin by creating a PHP function in our functions.php file. You need to make sure you are editing in-between the opening and closing PHP tags ().

You can call this function whatever you like. I’m going to call mine mytheme_files:

Then we will call a WordPress function called wp_enqueue_style(). This is what we use to enqueue a CSS stylesheet.

Now, we are going to use two parameters in this function. The first parameter is the name of the stylesheet. I’m going to call mine mytheme_main_style. We place this in between the brackets and place this within single quotation marks.

For the second parameter, we’re going to use the WordPress function get_stylesheet_uri(). This function gets the URI of the main stylesheet (i.e style.css) for the current theme.

We need to separate this parameter from the previous parameter with a comma, and we don’t need to place this within quotation marks.

So we’ve created our function, but our function won’t run until it’s called. To call our function we will use the WordPress function add_action(). This is placed outside of the function we have just created:

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); >add_action();

We are going to use two parameters within this function. The first parameter tells WordPress when to call the function, and for this, we are going to use wp_enqueue_scripts. Again, we need to place this within the brackets and within single quotation marks.

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); >add_action('wp_enqueue_scripts');

The second parameter tells WordPress which function to call. So, add a comma after the previous parameter and in single quotation marks, type in the name of the function we have created to enqueue our scripts. Remember, mine is called mytheme_files.

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); >add_action('wp_enqueue_scripts', 'mytheme_files');

And that it! That’s how we enqueue the style.css of a theme. Try this out and see if your style.css file is called in correctly.

But how do you enqueue a stylesheet that isn’t the main style.css file? After all, you may choose to use multiple stylesheets for a theme.

How to enqueue other stylesheets

So we know how to call in the main stylesheet of a WordPress theme, but what happens if you have other stylesheets with your theme files that you need to enqueue? For example, you might have a stylesheet that contains all the styling for mobile devices.

Well, we use a very similar method of enqueuing. We just need to change some parameters.

Instead of using get_stylesheet_uri() we will use get_theme_file_uri() function which gets the the URL of a file in the theme.

So let’s pretend we have a stylesheet in our theme folder called mobile.css. We can enqueue this stylesheet in the same function that we enqueued the main stylesheet in, so underneath our first wp_enqueue_style function, let’s add another one for our mobile.css file.

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); wp_enqueue_style(); > add_action('wp_enqueue_scripts', 'mytheme_files');

Again, give this stylesheet a name and make sure the name is in single quotation marks. I’m going to call mine mytheme_mobile_style.

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); wp_enqueue_style('mytheme_mobile_style'); > add_action('wp_enqueue_scripts', 'mytheme_files');

Then let’s add in our get_theme_file_uri() function:

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); wp_enqueue_style('mytheme_mobile_style', get_theme_file_uri()); > add_action('wp_enqueue_scripts', 'mytheme_files');

Now, to call in our stylesheet, we need to put the file name of this stylesheet in between the brackets like so:

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); wp_enqueue_style('mytheme_mobile_style', get_theme_file_uri('mobile.css')); > add_action('wp_enqueue_scripts', 'mytheme_files');

If the stylesheet is in a folder within the theme files then you will need to include this folder name too. For example, your stylesheet might be in a folder called css, so this is how you would enqueue that file:

function mytheme_files() < wp_enqueue_style('mytheme_main_style', get_stylesheet_uri()); wp_enqueue_style('mytheme_mobile_style', get_theme_file_uri('css/mobile.css')); > add_action('wp_enqueue_scripts', 'mytheme_files');

And that’s how we enqueue a stylesheet that isn’t the main stylesheet of a theme. Make sure you test this to make sure it works!

How to enqueue stylesheets from external websites

Sometimes you will want to enqueue stylesheets from external websites, for example, if you use Font Awesome or Google Fonts. To do this, we can use the wp_enqueue_style() function again in the functions.php.

Again, the first parameter will be the name of your file, but the second parameter will be the URL of the stylesheet just with the http: or https: removed from it.

So let’s look at an example. I want to enqueue a stylesheet from Google Fonts for the Roboto font. The stylesheet URL I am given is https://fonts.googleapis.com/css?family=Roboto. This is what it would look like in my functions.php file:

function mytheme_files() < wp_enqueue_style('mytheme_font', '//fonts.googleapis.com/css?family=Roboto'); > add_action('wp_enqueue_scripts', 'mytheme_files');

How to enqueue script files

Enqueuing a script file, such as a JavaScript file, is very similar to enqueuing a stylesheet in WordPress.

Instead of using the wp_enqueue_style() function we use the wp_enqueue_script() function. So let’s take a look at this in more detail

Start by creating a new function in your functions.php. Or if you have already set up a function to enqueue your stylesheets you can place your wp_enqueue_script() function within that.

Now we will place out wp_enqueue_script() function inside this function:

function mytheme_files() < wp_enqueue_script(); > add_action('wp_enqueue_scripts', 'mytheme_files');
wp_enqueue_script( 'script', get_theme_file_uri('/js/script.js'), NULL, '1.0', true);

Now we are going to use a number of parameters within this function. The first parameter is going to be a name for your script file. I’m going to call mine mytheme_script

function mytheme_files() < wp_enqueue_script('mytheme_script'); > add_action('wp_enqueue_scripts', 'mytheme_files');

Then for the second parameter, we are going to use the get_theme_file_uri() function that we used when we enqueued our stylesheets.

function mytheme_files() < wp_enqueue_script('mytheme_script', get_theme_file_uri()); > add_action('wp_enqueue_scripts', 'mytheme_files');

Within the brackets inside this function, we are going to type in the file name of the script file we want to enqueue. And remember, if the script file is in a folder, include this too.

In this example, my script file is called script.js so it would look like this:

function mytheme_files() < wp_enqueue_script('mytheme_script', get_theme_file_uri('script.js')); > add_action('wp_enqueue_scripts', 'mytheme_files');

And if my script was in a folder called js, it would look like this:

function mytheme_files() < wp_enqueue_script('mytheme_script', get_theme_file_uri('js/script.js')); > add_action('wp_enqueue_scripts', 'mytheme_files');

Ok, we aren’t finished just yet! Two parameters were enough to enqueue a stylesheet but we add in a few more parameters before our scripts are enqueued.

The next parameter we are going to add in is an array. This array handles any script that your script file depends on, such as jQuery. You can leave this blank if your script file doesn’t depend on any scripts.

function mytheme_files() < wp_enqueue_script('mytheme_script', get_theme_file_uri('js/script.js'), array()); > add_action('wp_enqueue_scripts', 'mytheme_files');

After this, we are going to add in a version number. This can be anything you want but I’m just going to use 1.0.

function mytheme_files() < wp_enqueue_script('mytheme_script', get_theme_file_uri('js/script.js'), array(), '1.0'); > add_action('wp_enqueue_scripts', 'mytheme_files');

The final parameter we are going to add in is a boolean parameter (which means you can either enter true or false) that allows you to choose where your script sits into your HTML document. So if you enter true your scripts will be loaded through wp_footer() and if you enter false they will be loaded through wp_head().

As this is a boolean parameter, you do not need to put it in quotation marks.

function mytheme_files() < wp_enqueue_script('mytheme_script', get_theme_file_uri('js/script.js'), array(), '1.0', true); > add_action('wp_enqueue_scripts', 'mytheme_files');

And that’s how we enqueue a script file. Don’t forget to test this to make sure it works!

Hot off the Word Press!

Join my FREE email community today to receive helpful tips and advice on building and maintaining your website directly in your inbox every other Friday. Just pop in your name and email address.

Источник

Подключаем правильно файлы стилей css в шаблоне WordPress

Подключать стили в шаблон в файле header.php — неправильно.
Правильная практика — подключать их в файле functions.php используя функцию wp_enqueue_style .
Это позволяет правильно добавить файл CSS стилей. Зарегистрировать файл стилей, если он еще не был зарегистрирован.

wp_enqueue_style() как и wp_enqueue_script() принято вызывать во время событий: wp_enqueue_scripts и admin_enqueue_scripts .

Подключаем файлы стилей .css через functions.php

Использование

wp_enqueue_style( $handle, $src, $deps, $ver, $media );

$handle (строка) (обязательный)
Название файла стилей (идентификатор). Строка в нижнем регистре. Если строка содержит знак вопроса (?): scriptaculous?v=1.2 , то предшествующая часть будет названием скрипта, а все что после будет добавлено в УРЛ как параметры запроса. Так можно указывать версию подключаемого скрипта.

$src (строка/логический)
УРЛ к файлу стилей. Например, http://site.ru/css/style.css . Не нужно указывать путь жестко, используйте функции: plugins_url() (для плагинов) и get_template_directory_uri() (для тем). Внешние домены можно указывать с неявным протоколом //notmysite.ru/css/style.css .
По умолчанию: false

$deps (массив)
Массив идентификаторов других стилей, от которых зависит подключаемый файл стилей. Указанные тут стили, будут подключены до текущего.
По умолчанию: array()

$ver (строка/логический)
Строка определяющая версию стилей. Версия будет добавлена в конец ссылки на файл: ?ver=3.5.1. Если не указать (установлено false), будет использована версия WordPress. Если установить null, то никакая версия не будет установлена.
По умолчанию: false

$media (строка/логический)
Устанавливается значение атрибута media. media указывает тип устройства для которого будет работать текущий стиль. Может быть: ‘all’, ‘screen’, ‘handheld’, ‘print’ или ‘all (max-width:480px)’. Полный список смотрите здесь.
По умолчанию: ‘all’

Подключение через событие

В этом примере, мы зарегистрируем и подключим стили и скрипты, используя событие ‘wp_enqueue_scripts’ .

// правильный способ подключить стили и скрипты add_action( ‘wp_enqueue_scripts’, ‘theme_name_scripts’ ); // add_action(‘wp_print_styles’, ‘theme_name_scripts’); // можно использовать этот хук он более поздний function theme_name_scripts()

Рабочий пример

/* Load Styles */ function crea_load_styles() < wp_enqueue_style('bootstrap-css', get_template_directory_uri() . '/libs/bootstrap-grid/css/bootstrap.min.css'); wp_enqueue_style('fa-css', get_template_directory_uri() . '/libs/font-awesome-4.7.0/css/font-awesome.min.css'); wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Ubuntu:300,400,500,700&subset=cyrillic'); wp_enqueue_style('main-style', get_template_directory_uri() . '/css/style.css'); wp_enqueue_style('style', get_stylesheet_uri()); >add_action('wp_enqueue_scripts', 'crea_load_styles', 10);

Число «10» в этой строке add_action(‘wp_enqueue_scripts’, ‘crea_load_styles’, 10); позволяет подключать наши стили в самую последнюю очередь после всех файлов стилей других плагинов.

15 ноября 2017 года был выпущен WordPress версии 4.9, названный в честь джазового музыканта Билли…

Регистрируем панель виджетов, в которую потом будем размещать виджеты на сайте, я обычно использую такие…

Регистрируем и выводим произвольное меню, созданное в панели: «Внешний вид > Меню» (Appearance > Menus)….

Используя PHP можно загружать содержимое SVG-файлов без лишних запросов к серверу, без использования img или…

Источник

Оцените статью