Looking around for when <scripts>
are focused on during the WP process, I found the following action hooks that are registered.
// In default-filters.php of WP core add_action( 'wp_head', 'wp_enqueue_scripts', 1 ); ... add_action( 'wp_head', 'wp_print_styles', 8 ); add_action( 'wp_head', 'wp_print_head_scripts', 9 ); ... add_action( 'wp_footer', 'wp_print_footer_scripts', 20 ); ... add_action( 'wp_print_footer_scripts', '_wp_footer_scripts' );
First thing to notice is that there is a function called wp_enqueue_scripts() that is called almost first thing (priority 1) during the wp_head
action hook. Let’s see what that function does:
// In script-loader.php of WP core function wp_enqueue_scripts() { /** * Fires when scripts and styles are enqueued. * * @since 2.8.0 */ do_action( 'wp_enqueue_scripts' ); }
Something interesting WP devs do, create a wrapper for a do_action
. I guess that gives some flexibility and allows one to create a ‘sub-action’ (I don’t know if that would really be what its called). The end result being that any actions added to wp_enqueue_scripts hook will be called during priority 1 of the wp_head action.
The actions added to the wp_enqueue_scripts hook are functions we create that run the wp_register_script()
, wp_enqueue_script()
, wp_register_style()
, and wp_enqueue_style()
calls containing the scripts and styles we want to have on the page. These are WordPress core functions that will add your scripts and styles to a collection. It does not add them to the page.
The end result being that any actions added to `wp_enqueue_scripts` hook will be called during priority 1 of the wp_head action.
It is at the wp_head action at priority 8 and 9 when the styles and scripts destined to the <head>
section are output to the page’s markup.
Why do we have both ‘register’ and ‘enqueue’?
They both can take the same arguments and they both put your script in a collection of scripts that could be outputted/printed to the HTML page. In fact, you could just use the ‘enqueue’ functions and never use the ‘register’ function. The ‘enqueue’ function technically ‘registers’ the script. But there is good reason to sometimes only use the ‘register’ function. Let’s see when that is.
The order the scripts are placed on the page is very important as some scripts depend that another script is already on the page. For instance, jQuery is a common dependency for scripts to run. The collection of scripts we register or enqueue is ordered based on any dependencies you might have put in one of the arguments. While scripts can be either in the <head>
or <footer>
sections of a page, WordPress needs all the scripts registered or enqueued before the <head>
finishes outputting so it can determine the order of the collection. Actually, from the above code, we see that WordPress needs all scripts registered and/or enqueued before priority 8 and 9 of the wp_head action.
Ok, so…
When do we use wp_register_script() instead of wp_enqueue_script()?
In the wp_enqueue_scripts action, we want to only register a script when:
- The script can be printed in the <footer> section, AND
- we will determine later if this script needs to be on this page.
If we just register a script and never enqueue it, it will not be put on the page. On the other hand, if we register and later in the page creation process but before the wp_footer action, we enqueue that already registered script, it will be put on the page.
WordPress needs all scripts registered and/or enqueued before priority 8 and 9 of the wp_head action.
An example of when we would do this would be for JavaScript we wanted to add if the page content had a shortcode that needed it. We won’t know if a shortcode is in the content of the page/post until long past the wp_head action has run.
//if part of theme, in the theme's functions.php add_shortcode( 'jht_ideas', 'jht_ideas_app' ); add_action( 'wp_enqueue_scripts', 'jht_enqueue_scripts' ); function jht_enqueue_scripts() { wp_register_script('jhtscripts', get_bloginfo( 'stylesheet_directory' ) . '/js/dist/app.js', array('jquery'),'1.0.0',true); // 'true' here says put script in footer if possible. // 'array('jquery')' says this script depends on jquery. } function jht_ideas_app($atts, $content=null) { // do something here... wp_enqueue_script('jhtscripts'); // tell WP we want the jhtscripts on the page. $output = '<div id="jhtMain"></div>'; return $output; }
This code will allow us to only put our JavaScript on the page if the page/post has a shortcode in it.
When is the last point we can enqueue a registered script
Based on the core WP code, it is at priority 20 of the wp_footer action when the last of the scripts are placed on the page. The last point to enqueue any registered scripts and get them on the page would be at the wp_footer action. If you don’t put a priority argument when you add_action(), it will be placed in priority 10 before the _wp_footer_scripts is run at priority 20.
Why do we do all this?
Why not just enqueue everything and be done with it. The main reason is for performance and optimization of your web page. One gripe I have with some plugins is that they load all their css and javascript on every page of your site when it may not even need it for that page. It is always best to only load what is needed.
This article was inspired by the following blog post: https://mikejolley.com/2013/12/02/sensible-script-enqueuing-shortcodes/
jhtechservices.com
Загрузка скриптов для использования на всём сайте
Есть по меньшей мере 2 способа для добавления файлов JavaScript или других скриптов, чтобы в последствии использовать их на сайте. Вот как добавляются скрипты для «шапки» или «подвала» сайта в панели администратора практически в любой современной теме:
Эти боксы в основном используются для добавления скриптов вроде Google Analytics или скриптов онлайн-чата. Если в вашей теме таких боксов нет, можно внести правки в код файла functions.php:
add_action( 'wp_enqueue_scripts', 'wpsites_register_load_script' ); /** * @author Brad Dalton - WP Sites * @example http://wp.me/p1lTu0-a40 */ function wpsites_register_load_script() { wp_register_script( 'your-script', get_stylesheet_directory_uri() . '/js/your-script.js' ); wp_enqueue_script( 'your-script' ); }
Примечание: После однократной регистрации скрипта нет необходимости регистрировать его повторно; его можно вызывать в зависимости от указанных условий в функции wp_register_script:
add_action( 'wp_enqueue_scripts', 'wpsites_load_javascript_conditionally' ); function wpsites_load_javascript_conditionally() { if ( is_page('page-slug') ) { wp_enqueue_script( 'your-script' ); } }
Загрузка скриптов только для определенных страниц или постов
Качественные платные фреймворки и темы наподобие Genesis облегчают задачу по настройке WordPress путем вызова необходимых скриптов для каждой отдельной страницы или определенного типа постов. Под каждой страницей или постом вы найдете отдельный бокс для добавления скриптов.
Если в вашей теме таких боксов нет, кликните по вкладке «Настройки экрана» справа вверху и активируйте отображение боксов для скриптов на экране в режиме редактирования:

Если в вашей теме вообще не предусмотрены отдельные боксы для добавления скриптов, добавьте следующий код в конце файла functions.php. При этом не забудьте заменить значение ‘007’ на нужный вам page_id и указать верный путь расположения .js-файла для приведения скрипта в рабочее состояние:
add_action( 'wp_enqueue_scripts', 'wpsites_load_javascript_conditionally' ); /** * @author Brad Dalton - WP Sites * @example http://wp.me/p1lTu0-a40 */ function wpsites_load_javascript_conditionally() { if ( is_page('007') ) { wp_register_script( 'your-script', get_stylesheet_directory_uri() . '/js/your-script.js' ); wp_enqueue_script( 'your-script' ); } }
Загрузка скриптов для дочерней темы
Единственная разница между загрузкой скриптов для родительской и дочерней темы заключается в следующем:
- get_template_directory_uri() — используйте эту функцию для родительской темы.
- get_stylesheet_directory_uri() — используйте эту функцию для дочерней темы.
Приведенный ниже код следует применять для загрузки скриптов в зависимости от указанных условий в родительской теме:
add_action( 'wp_enqueue_scripts', 'wpsites_load_javascript_conditionally' ); /** * @author Brad Dalton - WP Sites * @example http://wp.me/p1lTu0-a40 */ function wpsites_load_javascript_conditionally() { if ( is_page('007') ) { wp_register_script( 'your-script', get_template_directory_uri() . '/js/your-script.js' ); wp_enqueue_script( 'your-script' ); } }
Загрузка скриптов при помощи кода
Просто создаем новую папку «js» в дочерней теме в корневой папке и туда помещаем наши файлы с расширением .js. По приведенному коду подразумевается, что ваш файл скрипта носит название your-script. Если вы назвали файл иначе, то и пути к файлу, а также имена файлов в коде тоже надо изменить.
Загрузка скриптов для настраиваемого фона
А вот код для популярной темы Metro, созданной StudioPress. Этот код также можно применять для дочерних тем на основе Genesis, чтобы добавить адаптивное фоновое изображение на сайте:
add_action( 'wp_enqueue_scripts', 'metro_enqueue_scripts' ); /** * @example http://wp.me/p1lTu0-a40 */ function metro_enqueue_scripts() { // Load scripts only if custom background is being used if ( ! get_background_image() ) return; wp_enqueue_script( 'metro-backstretch', get_bloginfo( 'stylesheet_directory' ) .
js/backstretch.js', array( 'jquery' ), '1.0.0' ); wp_enqueue_script( 'metro-backstretch-set', get_bloginfo('stylesheet_directory').'/js/backstretch-set.js' , array( 'jquery', 'metro-backstretch' ), '1.0.0' ); wp_localize_script( 'metro-backstretch-set', 'BackStretchImg', array( 'src' => get_background_image() ) ); }
Загрузка скриптов для плагинов вручную
Большинство плагинов, включающих в себя скрипты, также содержат и код для загрузки скриптов, так что от вас никаких дополнительных действий не потребуется. Но если вам попался плагин, который содержит только сам код или только PHP-скрипт, то вам пригодится вот этот метод для загрузки jQuery-скриптов в плагинах:
add_action( 'wp_enqueue_scripts', 'wpsites_load_jquery_script' ); /** * @author Brad Dalton - WP Sites * @example http://wp.me/p1lTu0-a40 */ function wpsites_load_jquery_script() { wp_register_script( 'your-script', plugins_url( '/js/your-script.js', __FILE__ ), array( 'jquery' ) ); wp_enqueue_script( 'your-script' ); }
Для загрузки скриптов применяется метод, аналогичный загрузке таблиц стилей CSS, включая функции wp_register и wp_enqueue для корректной обработки и взаимодействия с файлом style.css.
Плагин Simple Scripts
Если в вашей теме нет отдельных полей для добавления скриптов, можно просто установить вот этот плагин под названием Simple Scripts.
hostenko.com
/** * Show the setup wizard */ public function setup_wizard() { if (empty($_GET['page']) || 'wc-setup' !== $_GET['page']) { return; } $this->steps = array('introduction' => array('name' => __('Introduction', 'woocommerce'), 'view' => array($this, 'wc_setup_introduction'), 'handler' => ''), 'pages' => array('name' => __('Page Setup', 'woocommerce'), 'view' => array($this, 'wc_setup_pages'), 'handler' => array($this, 'wc_setup_pages_save')), 'locale' => array('name' => __('Store Locale', 'woocommerce'), 'view' => array($this, 'wc_setu.
mmerce'), 'view' => array($this, 'wc_setup_ready'), 'handler' => '')); $this->step = isset($_GET['step']) ? sanitize_key($_GET['step']) : current(array_keys($this->steps)); $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min'; wp_register_script('select2', WC()->plugin_url() . '/assets/js/select2/select2' . $suffix . '.js', array('jquery'), '3.5.2'); wp_register_script('wc-enhanced-select', WC()->plugin_url() . '/assets/js/admin/wc-enhanced-select' . $suffix . '.js', array('jquery', 'select2'), WC_VERSION); wp_localize_script('wc-enhanced-select', 'wc_enhanced_select_params', array('i18n_matches_1' => _x('One result is available, press enter to select it.', 'enhanced select', 'woocommerce'), 'i18n_matches_n' => _x('%qty% results are available, use up and down arrow keys to navigate.', 'enhanced select', 'woocommerce'), 'i18n_no_matches' => _x('No matches found', 'enhanced select', 'woocommerce'), 'i18n_ajax_error' => _x('Loading failed', 'enhanced select', 'woocommerce'), 'i18n_input_too_short_1' => _x('Please enter 1 or more characters', 'enhanced select', 'woocommerce'), 'i18n_input_too_short_n' => _x('Please enter %qty% or more characters', 'enhanced select', 'woocommerce'), 'i18n_input_too_long_1' => _x('Please delete 1 character', 'enhanced select', 'woocommerce'), 'i18n_input_too_long_n' => _x('Please delete %qty% characters', 'enhanced select', 'woocommerce'), 'i18n_selection_too_long_1' => _x('You can only select 1 item', 'enhanced select', 'woocommerce'), 'i18n_selection_too_long_n' => _x('You can only select %qty% items', 'enhanced select', 'woocommerce'), 'i18n_load_more' => _x('Loading more results…', 'enhanced select', 'woocommerce'), 'i18n_searching' => _x('Searching…', 'enhanced select', 'woocommerce'), 'ajax_url' => admin_url('admin-ajax.php'), 'search_products_nonce' => wp_create_nonce('search-products'), 'search_customers_nonce' => wp_create_nonce('search-customers'))); wp_enqueue_style('woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css', array(), WC_VERSION); wp_enqueue_style('wc-setup', WC()->plugin_url() . '/assets/css/wc-setup.css', array('dashicons', 'install'), WC_VERSION); wp_register_script('wc-setup', WC()->plugin_url() . '/assets/js/admin/wc-setup.min.js', array('jquery', 'wc-enhanced-select'), WC_VERSION); wp_localize_script('wc-setup', 'wc_setup_params', array('locale_info' => json_encode(include WC()->plugin_path() . '/i18n/locale-info.php'))); if (!empty($_POST['save_step']) && isset($this->steps[$this->step]['handler'])) { call_user_func($this->steps[$this->step]['handler']); } ob_start(); $this->setup_wizard_header(); $this->setup_wizard_steps(); $this->setup_wizard_content(); $this->setup_wizard_footer(); exit; }
hotexamples.com
Подключение JavaScript к WordPress
Данный код подключает JavaScript в header шаблона WordPress.
function my_scripts_method() { wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js' ); } add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
- my_scripts_method — название вашей функции, можно любое, какое придет на ум, без пробелов, в нижнем регистре;
- wp_enqueue_script — функция для подключения js файлов WordPress;
- custom — название скрипта, любое, главное не повторять при подключении нескольких скриптов;
- get_template_directory_uri() — указывает на то, что скрипт находится в папке с шаблоном сайта, путь к файлу;
- /js/custom.js — в данном случае подключаемый скрипт должен находиться в папке js, custom.js — название js файла;
Для увеличения скорости загрузки сайта логичнее подключать скрипты в footer сайта, если скрипт не участвует в отрисовке страницы.
Данный код подключает JavaScript в footer
шаблона WordPress.
function my_scripts_method() { wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js', true ); } add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
Все то же самое, только добавлено true — команда для подключения JavaScript в footer.
Подключение зависящих от библиотеки JQuery скриптов к WordPress
Подключение аналогично подключению JavaScript, в функции указывается лишь массив JQuery, для правильной работы скрипта.
function my_scripts_method() { wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js', array('jquery') ); } add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
array(‘jquery’) — указывает зависимость от библиотеки JQuery.
Здесь не указывается, в какую область шаблона подключать скрипт (footer или header), так как он в любом случае будет подключен сразу после библиотеки JQuery, в массиве зависящих от нее скриптов.
Можно указать версию подключаемого скрипта к WordPress
function my_scripts_method() { wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0'); } add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
‘1.0.0’ — Строка указывающая версию скрипта, если она у него есть.
Этот параметр используется для того чтобы удостовериться, что клиент получил верную версию скрипта, а не из кеша.
Если версия не проставлена, то WordPress сам присвоет свою версию. Если указать null, то никакая версия не будет добавлена.
Подключение стороннего скрипта к WordPress
В данном примере подключается скрипт bootstrap.min.js с сервера CDN Google.
function my_scripts_method() { wp_enqueue_script( 'bootstrap', '//ajax.googleapis.com/ajax/libs/jquery/3.3.7/bootstrap.min.js'); } add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
Подключение аналогично вышеперечисленным примерам, только указан адрес стороннего скрипта. Протокол https: не указывается.
Подключение скрипта к дочерней теме WordPress
add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); function my_scripts_method(){ wp_enqueue_script( 'my-script', get_stylesheet_directory_uri() . '/patch/to/js/my-script.js', array( 'jquery' ), true ); }
Перерегистрация, обновление библиотеки jQery
Иногда нужно поменять библиотеку jQery WordPress на более свежую. Для этого нужно использовать такой код:
function my_scripts_method() { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', get_template_directory_uri() . '/inc/js/jquery.min.js', false, null, true ); wp_enqueue_script( 'jquery' ); } add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
svsites.ru
CDN
You might wanna use one of available CDN’s for your third party libraries to get all advantages that are listed in this answer.
E.g. If you use Google’s or Facebook’s CDN, there is a big chance, that your visitors already got popular scripts cached in their browsers and wouldn’t need to download it again.
In that case, bundling 3rd party scripts takes away this advantage, and the whole bundle needs to be downloaded, even if the user has part of it already saved in browser’s cache.
You can easily enqueue scripts from CDN with wp_enqueue_script()
, just omit the $ver
parameter, ’cause you don’t want to refresh the cached script:
wp_enqueue_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', [], null, true );
Conditional tags
The other thing I would consider is registering more scripts and calling them only on pages where they are actually used. This works well especially if you update your scripts often.
If you keep all scripts in a bundle, applying one little changes requires busting cache for the whole script. Sometimes it might be better to keep parts of your scripts separated, so you can change version only for the chunk that you actually edited.
Let’s say I use foo.js
script on my homepage and there’s not much going on there so I don’t plan to change it anytime soon, but at the same time I have a complicated bar.js
script that I need to maintain and refresh often. In that case it might be better to register scripts separately.
Also, some of your libraries might be used only on subpages that are not visited very often (let’s say I use masonry
on one less popular subpage), so preloading them on your home page might not be the way to go. In that case I’d do: // register masonry but don’t enqueue it just yet wp_register_script( ‘masonry’, get_template_directory_uri() . ‘/assets/js/masonry.min.js’, [], 1.0, true );
// foo.js is my implementation of masonry.js wp_register_script( 'foo.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [ 'masonry' ], 1.0, true ); // in bar.js I keep functions used all over my page so I enqueue it everywhere immediately wp_enqueue_script( 'bar.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [], 1.0, true ); // masonry.js and foo.js can wait until the user reaches my less popular subpage as it won't be needed most of the time if ( is_post_type_archive( 'unpopular-posts' ) ){ wp_enqueue_script( 'foo.js' ); }
wordpress.stackexchange.com
CDN
Вы можете использовать один из доступных CDN для своих сторонних библиотек, чтобы получить все преимущества, перечисленные в этом ответе .
Например, если вы используете CDN от Google или Facebook, есть большая вероятность, что ваши посетители уже получили популярные скрипты, кэшированные в своих браузерах, и больше не нужно будет загружать их.
В этом случае связывание сторонних скриптов убирает это преимущество, и весь пакет необходимо загрузить, даже если пользователь уже часть его уже сохранена в кеше браузера.
Вы можете легко вставить скрипты из CDN с помощью wp_enqueue_script()
, просто опустите параметр $ver
, потому что вы не хотите обновлять кешированный скрипт:
wp_enqueue_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', [], null, true );
Условные теги
Другая вещь, которую я хотел бы рассмотреть, – регистрировать больше скриптов и называть их только на тех страницах, где они фактически используются. Это хорошо работает, особенно если вы часто обновляете свои скрипты.
Если вы храните все скрипты в наборе, для применения одного небольшого изменения требуется перебор кеша для всего скрипта. Иногда было бы лучше, если бы части ваших сценариев были разделены, поэтому вы можете изменять версию только для фрагмента, который вы фактически редактировали.
Предположим, я использую скрипт foo.js
на своей домашней странице, и там не так много происходит, поэтому я не планирую менять его в ближайшее время, но в то же время у меня есть сложный скрипт bar.js
который мне нужно поддерживать и обновлять довольно часто. В этом случае было бы лучше зарегистрировать сценарии отдельно.
Кроме того, некоторые из ваших библиотек могут использоваться только на подстраницах, которые не часто посещаются (скажем, я использую masonry
на одной менее популярной подстранице), поэтому предварительная загрузка их на вашей домашней странице может быть не такой. В этом случае я бы сделал: // зарегистрировал кладку, но не ставил ее в очередь только wp_register_script ('masonry', get_template_directory_uri (). '/assets/js/masonry.min.js', [], 1.0, true) ;
// foo.js is my implementation of masonry.js wp_register_script( 'foo.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [ 'masonry' ], 1.0, true ); // in bar.js I keep functions used all over my page so I enqueue it everywhere immediately wp_enqueue_script( 'bar.js', get_template_directory_uri() . '/assets/js/masonry.min.js', [], 1.0, true ); // masonry.js and foo.js can wait until the user reaches my less popular subpage as it won't be needed most of the time if ( is_post_type_archive( 'unpopular-posts' ) ){ wp_enqueue_script( 'foo.js' ); }
www.wordpressask.com
Подключаем файлы скриптов .js
через functions.php
jQuery регистрируется в WP по умолчанию. Поэтому для его подключения достаточно одной строки:
wp_enqueue_script('jquery');
Зарегистрировать и подключить новый скрипт (скрипт подключится в <head>
):
wp_enqueue_script('modernizr-js', get_template_directory_uri() . '/libs/modernizr/modernizr.js');
Чтобы подключить скрипт в футере после основного содержимого, можно использовать такой формат:
wp_enqueue_script('modernizr-js', get_template_directory_uri() . '/libs/modernizr/modernizr.js', array(), false, true);
jQuery можно не подключать дополнительно, если один из скриптов указывает на зависимость от jQuery array('jquery')
, то есть библиотека jQuery подключится вместе с этим скриптом.
Кстати, библиотека jQuery подключается в <head>
из-за того, что много других скриптов и плагинов зависят от нее, и поэтому она должна быть подключена в первую очередь.
Использование
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
Шаблон использования
add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); function my_scripts_method(){ wp_enqueue_script( 'newscript', get_template_directory_uri() . '/js/custom_script.js'); }
Параметры
$handle (строка) (обязательный)
Название скрипта (рабочее название). Строка в нижнем регистре.
Если строка содержит знак вопроса (?): scriptaculous&v=1.2
, то предшествующая часть будет названием скрипта, а все что после будет добавлено в УРЛ как параметры запроса. Так можно указывать версию подключаемого скрипта.
$src (строка)
УРЛ файла скрипта. Например: http://example.com/wp-content/themes/my-theme/my-theme-script.js
.
Этот параметр необходим только, когда скрипт не зарегистрирован и WordPress еще не знает об этом скрипте, смотрите функцию wp_register_script()
.
Не нужно писать УРЛ жестко, он должен определяться динамически. Для этого используйте функции получения URL:
plugins_url()
— для плагинов
get_template_directory_uri()
— для тем.
Ссылки на внешние скрипты можно указывать без указания протокола: //otherdomain.com/js/their-script.js
.
Уже зарегистрированные в WP скрипты смотрите ниже в этой статье.
По умолчанию: false
$deps (массив)
Массив названий скриптов от которых зависит этот скрипт; скрипты которые должны быть загружены перед этим скриптом. Этот параметр необходим только в случае, если WordPress еще не знает об этом скрипте.
По умолчанию: array()
$ver (строка)
Строка указывающая версию скрипта, если она у него есть. Этот параметр используется для того чтобы удостовериться, что клиент получил верную версию скрипта, а не из кеша.
Если параметр не указан, то в качестве версии скрипта будет использована версия WordPress.
Если указать null
, то никакая версия не будет добавлена.
По умолчанию: false
$in_footer (логический)
Подключить скрипт в подвал?
Обычно скрипт подключается в <head> документа, если указать true, то скрипт будет подключен перед тегом </body>, точнее там где вызывается тег шаблона wp_footer()
.
Если из-за зависимости от других скриптов нет возможности подключить текущий скрипт в подвале, то значение этой переменой будет проигнорировано.
Для понятного чтения кода, вместо true можно указать любую строку, например 'in_footer'
.
По умолчанию: false
Рабочий пример
Примерно в таком формате я подключаю скрипты на своих сайтах.
/* Load Scripts */ function crea_load_scripts() { // подключаем скрипт modernizr.js в <head> wp_enqueue_script('modernizr-js', get_template_directory_uri() . '/libs/modernizr/modernizr.js', array(), NULL, true); // вместо библиотеки jQuery из состава WordPress подключаем её CDN-копию (только при острой необходимости) wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', array(), NULL, false); wp_enqueue_script( 'jquery' ); // подключаем bootstrap.min.js с внешнего CDN-хранилища wp_enqueue_script('bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js', array(), NULL, true); // подключаем скрипт common.js из нашего локального шаблона и указываем его зависимость от jQuery wp_enqueue_script('common-js', get_template_directory_uri() . '/js/common.js', array('jquery'), NULL, true); } add_action('wp_enqueue_scripts', 'crea_load_scripts', 10);
Число «10» в этой строке add_action('wp_enqueue_scripts', 'crea_load_scripts', 10);
позволяет подключать наши скрипты в самую последнюю очередь после всех скриптов других плагинов.
Пример, как подключить скрипт для определенной страницы
add_action( 'template_redirect', 'my_custom_readmore_script' ); function my_custom_readmore_script() { if ( is_page_template('template-best-reviews.php') ) { wp_enqueue_script( 'readmore-script', get_template_directory_uri().'/js/readMore.js', array( 'jquery' ), false, true ); } }
Более подробно — здесь https://wp-kama.ru/function/wp_enqueue_script.
denis-creative.com
Как правильно подключать CSS и скрипты в WordPress.
Создаю эту страницу для того, чтобы было удобно скопировать-вставить в проект готовую конструкцию. В файле functions.php создаём следующую функцию:
- Параметры для wp_register_style:
wp_register_style( $handle, $src, $deps, $ver, $media );
$handle — имя файла, $src — URL до css файла , $deps — массив названий стилей от которых зависит добавляемый (они должны быть зарегистрированы ранее), $ver — версия стиля, $media — список типов устройств или медиа для которых предназначен данный стиль.
- Параметры для wp_register_script
wp_register_script( string $handle, string $src, array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )
Все параметры — те же, что и у предыдущей функции, кроме последнего. $in_footer — если true, то скрипт будет вставлен в footer до </body> вместо <head>. По-умолчанию ‘false’.
- Параметры для wp_enqueue_script и wp_enqueue_style.
При регистрации script файлов и файлов стилей при помощи функций wp_register_script и иwp_register_style никаких дополнительных параметров (кроме зарегистрированного имени скрипта/стиля) указывать не нужно.
Полезные дополнения.
- wp_dequeue_style(‘my_style’) — удаляет из очереди на вывод css файл стилей. Если на некоторых страницах не нужно выводить этот файл, тогда его можно отключить.
- wp_style_is() определяет был ли файл стилей зарегистрирован, добавлен в очередь на вывод, выведет на экран или ожидает вывода.
- wp_style_add_data() — добавляет данные для подключаемых с помощью wp_enqueue_style() файлов стилей. Используйте когда, например нужно подключить стили только для IE.
WordPress как подключить определенные стили/скипты только на одной странице?
is_single — для записи
is_page — для страниц
www.mywebtoday.ru