Upload
dimakuzovlev
View
132
Download
0
Embed Size (px)
Citation preview
Вёрстка тем
План
3
1. Содержимое WordPress темы
a. Файлы шаблонов
b. Иерархия шаблонов
2. CSS & JS
a. Тонкости подключения
b. Полезные функции
3. О functions.php
a. Что не стоит добавлять в functions.php?
b. Какие альтернативы существуют?
4. Кастомные шаблоны. Продвинутое назначение шаблона
5. Зачем нужна дочерняя тема и как её создать?
6. Правила разработки и отладка в WordPress
Как устроена тема WordPress
4
/wp-content/themes/my-theme/...
style.css
5
/*
Theme Name: Twenty Fifteen
Theme URI: https://wordpress.org/themes/twentyfifteen
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Our 2015 default theme is clean, blog-focused, and
designed for clarity...
Version: 1.0
License: GNU General Public License v2 or later
*/
/* Theme styles are here */
...
Файлы шаблонов
6
Home Templates:
front-page.phphome.php
Static Page Templates:
custom-page.phppage-contact.phppage-3.phppage.php
Archive Templates:
author.phpcategory.phptag.phpdate.phptaxonomy.phparchive.php
Single Templates:
attachment.phpsingle.phpsingle-product.php
Search Results Template:
search.php
Error 404 Template:
404.php
index.php
Иерархия шаблонов WordPress
7http://codex.wordpress.org/Template_Hierarchy
Archive Pages
8
Static Page
Модульные файлы шаблонов
9
/wp-content/themes/my-theme/...
header.php
sidebar.php
footer.php
tpl.part-gallery.php
get_header()
header-product.php get_header( 'product' )
get_sidebar()
get_footer()
get_template_part( 'tpl.part', 'gallery' )
searchform.php get_search_form()
comments.php comments_template()
CSS & JSТонкости подключения
10
Подключение CSS & JS
11
header.php:
<head>...<link rel="stylesheet" href="http://mysite.com/css/style.css" ><script src="http://mysite.com/js/my-script.js" ></script>...
</head>
functions.php:
function add_js_css_to_head () { echo '<link rel="stylesheet" ref="http://mysite.com/css/style.css">' ; echo '<script src="http://mysite.com/js/my-script.js"></script>' ;}add_action( 'wp_head', 'add_js_css_to_head' );
Подключение CSS & JS
12
header.php:
<head>...<link rel="stylesheet" href="http://mysite.com/css/style.css" ><script src="http://mysite.com/js/my-script.js" ></script>...
</head>
functions.php:
function add_js_css_to_head () { echo '<link rel="stylesheet" ref="http://mysite.com/css/style.css">' ; echo '<script src="http://mysite.com/js/my-script.js"></script>' ;}add_action( 'wp_head', 'add_js_css_to_head' );
13
Функции регистрации CSS & JS
wp_register_style( $handle, // *идентификатор$src, // *URL к файлу стилей$depends, // массив идентификаторов стилей, от которых зависит регистрируемый$version, // номер версии$media // медиа-тип ('all', 'screen', 'handheld' или 'print')
); wp_register_script(
$handle, // *идентификатор$src, // *URL к скрипту$depends, // массив идентификаторов скриптов, от которых зависит регистрируемый$version, // номер версии$in_footer // где выводить скрипт ('wp_head' или 'wp_footer')?
);
Функции подключения CSS & JS
wp_enqueue_style( $handle ); wp_enqueue_script( $handle );
http://codex.wordpress.org/Function_Reference/wp_register_stylehttp://codex.wordpress.org/Function_Reference/wp_register_scripthttp://codex.wordpress.org/Function_Reference/wp_enqueue_style
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
Хуки для подключения CSS & JS
14
Frontend :
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' );add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_script' );
Backend (admin panel) :
add_action( 'admin_enqueue_scripts', 'mytheme_enqueue_style' );add_action( 'admin_enqueue_scripts', 'mytheme_enqueue_script' );
Login Page :
add_action( 'login_enqueue_scripts', 'mytheme_enqueue_style' );add_action( 'login_enqueue_scripts', 'mytheme_enqueue_script' );
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scriptshttp://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scriptshttp://codex.wordpress.org/Plugin_API/Action_Reference/login_enqueue_scripts
Полный код подключения CSS & JS
15
function register_and_enqueue_style() {wp_enqueue_style( 'my-style', get_stylesheet_directory_uri() . '/css/my-style.css', array( 'bootstrap-main' ), '1.0.1', 'screen');
} function register_and_enqueue_script() {
wp_enqueue_script( 'my-script',get_stylesheet_directory_uri() . '/js/my-script.js',array( 'jquery' ),'1.0.1'
);} add_action( 'wp_enqueue_scripts', 'register_and_enqueue_style' );add_action( 'wp_enqueue_scripts', 'register_and_enqueue_script' );
CSS: Полезные функции
16
Добавление inline-стилей ( <style>/* inline styles*/</style> ) :
wp_add_inline_style( 'my-style', "h2 { font-family: { $font_family }; }" );
Был ли CSS файл зарегистрирован / добавлен в очередь / выведен / ожидает вывода:
wp_style_is( 'my-style', 'registered' /* or 'enqueued', 'done', 'to_do' */ );
Подключение стилей для Internet Explorer :
wp_style_add_data( 'my-style-ie', 'conditional', 'lt IE 9' );
Удаление CSS файла из очереди вывода стилей :
wp_dequeue_style( 'my-style' );
Отмена регистрации CSS файла :
wp_deregister_style( 'my-style' );
JS: полезные функции
17
Локализация JavaScript :
wp_localize_script( 'my-script', 'object_name', array('count' => 5,'color' => $color
));
Был ли JS файл зарегистрирован / добавлен в очередь / выведен / ожидает вывода:
wp_script_is( 'my-style', 'registered' /* or 'enqueued', 'done', 'to_do' */ );
Удаление JS файла из очереди вывода скриптов :
wp_dequeue_script( 'my-script' );
Отмена регистрации JS файла :
wp_deregister_script( 'my-script' );
О functions.php...
18
● Лежит в корне темы: /wp-content/themes/my-theme/functions.php
● Загружается при запросе любой страницы (включая админку)
● Выполняется только тогда, когда тема активирована
Позволяет:● Определять дополнительные функции
● Переопределять существующие функции
● Устанавливать различные параметры для ядра WordPress
● Изменять поведение Wordpress через хуки и фильтры
Когда использовать functions.php
19
● Объявление сайдбаров для виджетов темы
● Определение путей к файлам локализации темы
● Включение поддержки темой различных Wordpress фич ('post-formats', 'post-thumbnails', 'widgets', 'menus' ...)
● Подключение скриптов и стилей для темы
● Создание раздела с настройками темы
● Дополнительные функции используемые в шаблонах темы
● Регистрация новых размеров миниатюр для темы
Когда не использовать functions.php
20
● Код счетчиков Google Analytics или Яндекс.Метрики
● Добавление кастомных типов контента и таксономий
● Регистрация дополнительные ролей и возможностей пользователей
● Добавление шорткодов
Если не в functions.php, то куда?
21
Regular Plugin Must Use Plugin
Кастомный шаблон
22
/wp-content
/themes
/my-theme
/custom-template.php
Продвинутое назначение шаблона
23
function custom_templates( $template ) {
global $post;
$post_format = get_post_format( $post->ID );
$has_thumb = has_post_thumbnail( $post->ID );
if( is_single() && $post_format === 'gallery' && $has_thumb ){
if ( $new_template = locate_template( array( 'custom-template.php' ))) {
return $new_template;
}
}
return $template;
}
add_filter( 'template_include', 'custom_templates' );
Дочерняя тема в WordPress
Who’syour
(theme’s)daddy?
24
Дочерняя WP тема
“A child theme is a theme that inherits the functionality and styling of another theme, called the parent theme. Child themes are the recommended way of modifying an existing theme.”
- The WordPress Codex
http://codex.wordpress.org/Child_Themes
25
Дочерняя Wordpress тема:● имеет родительскую тему● лежит в папке /wp-content/themes/ с остальными темами● наследует внешний вид и весь функционал родительской темы
… и применяется если необходимо:● вносить изменения в родительскую тему● кастомизировать дизайн родительской темы● расширить возможности родительской темы новым функционалом
26
/wp-content
/themes
/twentyfifteen/twentyfifteen-child
Создаём дочернюю тему
27
/twentyfifteen-child
/style.css
/screenshot.png
/wp-content
/themes
/twentyfifteen
Перегрузка шаблонов
28
/wp-content/themes/twentyfifteen /wp-content/themes/twentyfifteen-child
functions.php и дочерняя тема
29
if ( ! function_exists( 'theme_special_nav' ) ) {
function theme_special_nav () {
// Do something.
}
}
Правила разработки
Стандарты кодирования
31
● повышаем читаемость своего кода
● упрощаем чтение и понимание исходников WordPress
● говорим с другими разработчиками на одном языке
https://make.wordpress.org/core/handbook/coding-standards/php/
https://make.wordpress.org/core/handbook/coding-standards/javascript/
https://make.wordpress.org/core/handbook/coding-standards/html/
https://make.wordpress.org/core/handbook/coding-standards/css/
Debugging in WordPress
32
// Включаем режим отладки в wp-config.php
define( 'WP_DEBUG', true );
http://codex.wordpress.org/Debugging_in_WordPress
Логирование ошибок
33
// Включаем логирование в wp-config.phpdefine( 'WP_DEBUG', true );define('WP_DEBUG_LOG', true);
// Выключаем отображение ошибок на сайтеdefine('WP_DEBUG_DISPLAY' , false);
CSS & JS debug
34
// Подключаем dev версии JS & CSS файловdefine('SCRIPT_DEBUG', true);
Плагин Debug Bar
35
● Notices / Warnings● потребляемая память● выполненные SQL запросы
https://wordpress.org/plugins/debug-bar/
● состояние объектного кэширования● информация о запросе WP_Query● использование устаревших функций
Вопросы?
Спасибо!