О WordPress

Ох уж этот WordPress!

Список интересных плагинов

На этой страницы я собрал список плагинов, которые могут представлять интерес для использования на ваших сайтах. Собственно, любой плагин WordPress может представлять интерес, но эти я сам использую и они мне нравятся, а также имеют большое количество активных установок.

Удобство работы и администрирования сайта

Classic Editor — позволяет вернуть классический редактор при создании публикаций вместо новомодного редактора блоков.

Revision Control — как известно, при обновлении публикации, WordPress сохраняет предыдущую редакцию как ревизию, которую с помощью данного плагина можно вернуть обратно. А также можно удалить все старые версии публикации и таким образом почистить базу от ненужных дублей.

TinyMCE Advanced — позволяет заменить ограниченный набор функций классического редактора на расширенный визуальный редактор TinyMCE.

WP Super Cache — наиболее популярный плагин кэширования публикаций.

User Role Editor — редактор прав пользователей для конкретных ролей. Вы можете изменить предустановленные права работы с WordPress для стандартных ролей, а также создать собственные роли с необходимыми вам правами.

Разработка

Simple Custom CSS and JS — плагин, позволяющий добавить произвольный CSS и/или JavaScript на ваш сайт. Очень удобно, если нужно поправить стили темы оформления, а она не содержит возможности указывать дополнительные стили и JavaScript.

Безопасность

WP Cerber Security — шикарный плагин, позволяющий повысить безопасность вашего сайта, заблокировав перебор паролей или даже вообще предоставить доступ в админку только по белому списку. Там же вы найдёте проверку файлов сайта по высчитанным ранее контрольным суммам и некоторые другие фичи.

Капча — позволяет вставить CAPTCHA (ввод кода с картинки) на страницы входа, регистрации и добавления комментариев.

Содержимое

Advanced Custom Fields — Самый популярный плагин для добавления дополнительных полей к публикациям. Часто стандартных полей (заголовок, тело публикации, категория, тег) недостаточно. Нужны и другие поля, например для характеристик товара или описания книги.

bbPress — позволяет создать на сайте форум. К сожалению, не все темы оформления нормально поддерживают работу форума. Поэтому надо либо искать соответствующую тему, либо писать к текущей теме оформления шаблоны/стили для отображения форума самостоятельно.

Breadcrumb NavXT — позволяет добавить в публикации цепочку навигации (хлебные крошки). К сожалению, только через правку шаблона публикации.

Compact Audio Player — позволяет добавить в публикации шорткод проигрывателя .mp3 или .ogg файлов. Не требует никаких дополнительных библиотек.

Custom Permalinks — позволяет задать произвольный URL для вашей публикации. По умолчанию WordPress предлагает очень ограниченный выбор автоматической генерации URL публикации. Используя данный плагин вы можете указать совершенно произвольный URL, неограниченный никакими шаблонами.

Custom Post Type UI — позволяет создавать кастомные типы публикаций и дополнительные кастомные таксономии. Используя данный плагин, вы можете добавить, например, ещё одну таксономию для категоризации, если одной вам недостаточно.

Cyr-To-Lat — плагин позволяет выполнить транслитерацию русскоязычного URL в латиницу, что повышает его читабельность и сокращает размер URL.

DrawIt (draw.io) — позволяет вставлять в публикации схемы и диаграммы, созданные на сайте http://draw.io в режиме онлайн. После вставки сохраняется возможность редактирования.

Easy Table of Contents — Добавляет удобный и полностью автоматический способ создания и отображения оглавления, созданного из содержимого страницы.

Easy Watermark — позволяет добавлять к загружаемым изображениям заданный текст или картинку. Полезно для маркировки ваших изображений, которые вы выкладываете на сайт авторскими отметками, например URL вашего сайта или указание копирайта и ФИО автора.

Embed Plus for YouTube — Gallery, Channel, Playlist, Live Stream — позволяет вставлять в публикации ролики с YouTube с помощью шорткода.

Google XML Sitemaps — пожалуй лучший плагин для генерации sitemap файлов в автоматическом режиме.

Kama WP Smiles — добавляет возможности использовать смайлики в публикации и комментарии.

OSM — добавляет возможность вставить фрагмент карты Open Streetmap в публикацию с указанием одного или нескольких маркеров объектов на карте. Не требует API ключей в отличие от Yandex Map или Google Map.

Page-list — плагин, предоставляющий шорткоды, которые выводят список заголовков дочерних или соседних страниц от текущей. Регулируется глубина обхода иерархии.

PHP Code Widget — включение возможности использовать вставки PHP кода в виджеты.

Relevanssi — на сегодняшний день, самый удобный поиск по сайту для русского языка. Морфологию и синонимы не понимает, но умеет искать по частям слов.

WP ULike — позволяет настроить голосование рейтинга публикации в виде звёздочек или лайков. Также работает и с комментариями.

WP User Avatar — Используйте любое изображение из вашей медиа библиотеки WordPress, как пользовательский аватар. Добавьте свой собственный стандартный аватар

Шорткоды — обширная коллекция шорткодов с разной функциональностью.

 

Настольная книга по разработке тем оформления

(перевод Theme Handbook с сокращениями, оставим только суть)

Добро пожаловать. Данная книга предназначена как для новичков, так и для опытных разработчиков, и содержит подробную информацию по всем аспектам разработки тем оформления в WordPress.

  1. Если вы новичок, начните с раздела 1, где вы можете прочитать о том что такое тема оформления, узнать о лицензии на WordPress, настроить среду разработки, и создать свою первую тему оформления.
  2. Если вы уже прошли вводный раздел, то раздел Основы темы оформления поможет вам разобраться в создании блоков темы оформления WordPress.
  3. Раздел Функционал тем оформления расскажет вам о разных типах функционала, который вы можете использовать в вашей теме оформления.
  4. Если вы хотите получить гибкость и защитить ваших пользователей, изучите разделы Кастомизация и Безопасность
  5. Если вы знакомы с основами тем оформления, прочтите Расширенные возможности тем оформления, чтобы узнать о дочерних темах, лучших практиках пользовательских интерфейсов, тестировании тем и многом другом.
  6. Если вы готовы поделиться своей темой оформления со всем миром, то в заключительном разделе вы узнаете как  выпустить вашу тему оформления, научитесь лучшим практикам распространения тем оформления и подготовке их к размещению в каталоге тем на WordPress.org.

Данная книга создана сообществом WordPress для сообщества WordPress. Мы всегда ищем новых авторов; если вам это интересно, загляните в блог команды документирования, чтобы узнать о том как стать участником.

Первые шаги

Вы готовы начать разработку тем оформления WordPress? Вы нашли верное место.

В данном разделе, вы прочтёте о том, что такое темы оформления WordPress и как они работают. Затем, обсудим лицензию GPL, которая является лицензий, используемой WordPress и всеми темами в каталоге WordPress.

Затем вы узнаете о некоторых инструментах, которые понадобятся вам при разработке тем оформления WordPress, а также о том как настроить локальную среду для разработки.

В конце данного раздела вы увидите некоторые примеры тем оформления WordPress.

Кто должен прочитать данную книгу?

Данная книга может научить вас основам разработки тем оформления WordPress. Вы должны прочитать данную книгу в случае если вы:

  • разрабатываете дочернюю тему, предназначенную для работы с родительской;
  • создаёте новую тему, на основе существующей;
  • хотите понять основы той работы, которая происходит внутри темы;
  • разрабатываете тему, основанную на вашем воображении;

Требуемый уровень

Чтобы извлечь максимальную пользу из этого руководства, вы должны иметь представление и опыт работы с веб-технологиями, такими как HTML, CSS и PHP. Вы также должны уметь устанавливать и настраивать веб-сайты с помощью WordPress.

Примечание. Понимание того, как работают базы данных MySQL, а также серверные технологии в целом, полезно, но не является обязательным условием для разработки тем оформления WordPress. Аналогично, хотя знание JavaScript может быть полезным, это не обязательно.

О чём рассказывает эта книга

Это руководство содержит основную информацию, необходимую для разработки тем оформления WordPress, включая подробное описание основных тегов и функций шаблона.

WordPress — обширная тема. Охват каждого возможного тега, функции и сценария выходит за рамки данного руководства. Если вам нужна помощь с конкретными функциями, вы можете найти эту информацию в справочнике по коду.

Цель данного руководства — дать вам прочную основу для разработки тем оформления WordPress, предоставить пошаговые инструкции по созданию базовых тем, а также предоставить советы и ресурсы, полезные для развития ваших навыков.

Что такое тема оформления?

Тема офрмления WordPress меняет дизайн вашего сайта, включая (и довольно часто) вёрстку. Изменение темы меняет внешний вид вашего сайта в интерфейсе, то есть то, что видит посетитель, когда он просматривает ваш сайт в Интернете. В каталоге тем WordPress.org есть тысячи бесплатных тем WordPress, хотя многие сайты WordPress используют собственные темы.

Что может делать тема оформления?

Темы оформления получают контент и данные, которые хранит WordPress, и отображают их в браузере. Когда вы создаете тему WordPress, вы решаете, как этот контент будет выглядеть и отображаться. Для создаваемой вами темы, доступно множество возможностей. Например:

  • Ваша тема может иметь разные макеты, такие как статические или адапливные, использовать одну колонку или две.
  • Ваша тема может отображать контент везде, где вы хотите, чтобы он отображался.
  • Ваша тема может задать, какие устройства или действия делают ваш контент видимым.
  • Ваша тема может настроить элементы оформления с помощью CSS.
  • Другие элементы дизайна, такие как изображения и видео, могут быть включены в любое место вашей темы.

Темы оформления WordPress невероятно мощные. Но, как и в любом проекте веб-дизайна, тема — это больше, чем цвет и макет. Хорошие темы улучшают взаимодействие с контентом вашего веб-сайта в дополнение к тому, чтобы быть красивыми.

Как сделана тема оформления?

На самом базовом уровне темы оформления WordPress представляют собой наборы различных файлов, которые работают вместе для создания того, что вы видите, а также поведения вашего сайта.

Требуемые файлы

Для темы оформления в WordPress строго необходимы только два файла:

  1. index.php – основной файл шаблона
  2. style.css – основной файл стилей

Не требуются, но могут быть дополнительно использованы в каталоге с темой такие файлы как:

  • файлы PHP  – включя файлы шаблона
  • Файлы локализации
  • CSS файлы стилей
  • Графические файлы
  • JavaScript
  • Текстовые файлы – обычно информация о лицензии, readme.txtинструкции и файл сделанных измененией — changelog

В чём разница между темой оформления и плагином?

Функции встречаются и в темах и плагинах. Тем не менее:

  • тема оформления управляет представлением контента;
  • плагин используется для управления поведением и возможностями сайта WordPress.

Любая тема, которую вы создаёте не должна предоставлять критическую для работы сайты функциональность. Такое будет означать, что если пользователь изменит свою тему оформления, он потеряет доступ к этой функциональности. Например, скажем, вы создаете тему с функцией портфолио. Пользователи, которые строят свое портфолио с помощью вашей функции, потеряют его при смене темы.

Перемещая критически важные функции в плагины, вы позволяете изменить дизайн своего веб-сайта, в то время как функциональность остается той же.

Примечание. Помните, что некоторые пользователи часто переключают темы. Лучше всего убедиться, что все функции, которые требуются вашему сайту, находятся в отдельном плагине.

 

Темы оформления на сайте WordPress.org

Одно из самых безопасных мест для загрузки тем WordPress — из каталога тем WordPress.org. Все темы тщательно проверяются и должны соответствовать строгим правилам проверки тем для обеспечения качества и безопасности.

Первые шаги

Теперь вы узнали, что такое тема и можете сделать первые шаги.  Если вы ещё не сделали это, настройте вашу локальную среду разработки. Затем вы можете ознакомится с некоторыми примерами тем оформления для WordPress или, если вам не терпится, приступайте к созданию вашей первой темы.

Лицензирование WordPress и GPL

Чтобы разрабатывать публичные темы оформления платные или бесплатные, вам необходимо ознакомится с лицензией GNU General Public License (сокращённо GPL), которую использует WordPress.

Основные свободы, которые предоставляет GPL

Дух открытости и желания делиться наработками процветает в сообществе WordPress благодаря фундаментальным принципам, которые описаны в его лицензии. Один из способов получить представление о GPL — это считать её неким аналогом «Билля о правах» для программного обеспечения. GPL устанавливает следующие четыре свободы:

  1. Свобода запускать программу для любых целей.
  2. Свобода изучать, как работает программа, и изменять ее, чтобы она делала то, что вы хотите.
  3. Свобода распространять копии, чтобы вы могли помочь другим.
  4. Свобода распространять копии изменённой вами программы, что дает сообществу возможность воспользоваться вашими изменениями.

Что есть “free” в контексте программного обеспечения?

Слово ‘free’ применительно к программному обеспечению, указывает на свободу и на бесплатность. Фонд «The Free Software Foundation» любит говорить “free as in speech, not as in beer.” («Бесплатно как слова, а не как пиво»). Свободное программное обеспечение — это то, которое может использоваться так, как вы хотите. Это не означает, что оно бесплатно, хотя это так для  каталога тем оформления на сайте WordPress.org.

Свободное программное обеспечение может иметь цену. Другими словами, вы можете создать тему под лицензией GPL и продать ее за 50 долларов, и все равно это будет свободное программное обеспечение. Почему? Поскольку пользователь может свободно запускать, модифицировать и распространять программное обеспечение или любые модификации этого программного обеспечения.

Оставляя свободным для всех…

Свободы лицензии GPL не только применяются к оригинальной части программного обеспечения; работы, являющиеся производными от программного обеспечения под лицензией GPL также должны распространяться под этой же лицензией, без ограничений и дополнительных условий.

В этом смысле, GPL предоставляет неограниченную защиту свободы программного обеспечения, давая уверенность, что любые производные от свободного программного обеспечения работы не могут быть «заблокированы» (закрыты); что должно оставить программное обеспечение свободным навсегда для будущих экспериментов и исследований.

Нужно ли лицензировать мои темы оформления под GPL?

Нет, если вы не планируете распространять вашу тему оформления каким-либо способом. В случае вашего индивидуального использования, вы можете не лицензировать ваши темы под GPL.

Если вы хотите отправить свое творение в бесплатный репозиторий тем на WordPress.org, то оно должно быть на 100% совместимо с GPL, включая CSS и файлы изображений. Поскольку свободы, изложенные в GPL, лежат в основе WordPress, мы призываем разработчиков распространять свои темы со 100% GPL-совместимой лицензией.

Примечание. Свобода является важной частью разработки тем WordPress. Если вы планируете распространять свою тему, рекомендуется полностью лицензировать ее под лицензией GPL, чтобы другие могли пользоваться теми же свободами, которые вы получили при ее создании.

Дополнительно можно почитать

Чтобы глубже понять WordPress и GPL вы можете почитать:

Настройка среды разработки

Почему нужно настроить среду разработки?

При разработке тем лучше всего делать это в среде, идентичной продуктивному серверу, на который в конечном итоге будет установлен WordPress. Ваша среда разработки может быть локальной или удаленной. Настройка локальной среды для работы над темой WordPress полезна по нескольким причинам:
  • Вы cможете создать свою тему локально, не полагаясь на удаленный сервер. Это ускоряет процесс разработки и позволяет мгновенно видеть изменения в вашем браузере.
  • Вам не нужно подключение к Интернету, чтобы создать свою тему.
  • Вы можете проверить свою тему с разных точек зрения. Это важно, особенно если вы планируете сделать свою тему для более широкой аудитории и хотите обеспечить максимальную совместимость

Ваша локальня среда разработки WordPress

Для разработки тем WordPress вам необходимо настроить среду разработки, подходящую для WordPress. Для начала вам понадобится стек локального сервера и текстовый редактор. Есть несколько вариантов, в том числе:

Стек локального сервера

  • LAMP (Linux Apache MySQL/MariaDB PHP) или WAMP (Windows Apache MySQL/MariaDB PHP) — это сервер (похожий на ваш веб-сервер), который вы настроите на вашей локальной машине. Для быстрого старта, вы можете установить предварительно подготовленные стеки MAMP (для Mac), или XAMPP (Mac или Windows).

Виртуализованная среда

  • Такая виртуализация, созданная с помощью Vagrant и VirtualBox, позволяет создавать легко воспроизводимые среды разработки. Varying Vagrant Vagrants (VVV) — это популярный вариант Vagrant, который создает среду разработки WordPress.

Текстовый редактор

В дополнение к среде локального сервера вам также понадобится текстовый редактор для написания кода. Ваш выбор текстового редактора является личным, но помните, что хороший текстовый редактор может ускорить процесс разработки. Ваш текстовый редактор может быть чем угодно, от базового инструмента для написания кода до полностью интегрированной среды разработки (IDE) с инструментами для отладки и тестирования. Некоторые даже включают поддержку разработки WordPress. Популярные варианты: Atom, Sublime Text и PhpStorm.

Вы можете найти список учебных пособий по настройке сред разработки в нижней части страницы.

Поддержка старых версий WordPress

Для тем WordPress является стандартной практикой поддержка на как минимум две версии назад для обеспечения минимальной обратной совместимости. Например, если текущая версия WordPress имеет версию 4.6, вам также следует убедиться, что ваша тема также хорошо работает в версиях 4.5 и 4.4.

Вы можете обратиться к странице дорожной карты WordPress для доступа к более старым версиям WordPress. Затем вы можете загрузить и установить более старые версии WordPress, создав для тестирования несколько сайтов разработки, на каждом из которых для будут использоваться разные версии WordPress.

WP_DEBUG

Настройка отладки является неотъемлемой частью разработки темы WordPress. WordPress предоставляет ряд констант для поддержки ваших усилий по отладке. Они включают:

WP_DEBUG

Константа PHP WP_DEBUG используется для запуска встроенного режима «отладки» в вашем WordPress. Это позволяет просматривать ошибки в теме оформления. Чтобы включить:

1. Откройте файл wp-config.php

2. Измените:

1
define( 'WP_DEBUG', false );

на

1
define( 'WP_DEBUG', true );

Примечание. Несмотря на то, что в файле wp-config.php обычно установлено значение «false», для рабочих копий WordPress — альфа- и бета-версий следующего выпуска — WP_DEBUG по умолчанию уже установлено значение «true».

WP_DEBUG_DISPLAY и WP_DEBUG_LOG

WP_DEBUG_LOG и WP_DEBUG_DISPLAY являются дополнительным константами PHP, которые расширяют поведение при включенном WP_DEBUG.

WP_DEBUG_LOG используется вместе с WP_DEBUG для записи всех сообщений об ошибках в debug.log в вашем каталоге WordPress / wp-content /. Чтобы включить эту функцию, установите для WP_DEBUG_LOG значение true в вашем файле wp-config.php.

1
define( 'WP_DEBUG_LOG', true );

WP_DEBUG_DISPLAY используется для управления отображением сообщений отладки в HTML на страницах вашей темы. Чтобы сообщения об ошибках отображались по мере их появления, настройте для этого параметра значение «true» в файле wp-config.php

1
define( 'WP_DEBUG_DISPLAY', true );

Если включены WP_DEBUG и WP_DEBUG_DISPLAY, сообщения об ошибках будут отображаться в верхней части страниц вашего сайта.

Примечание. Ошибки будут отображаться во внешней и административной областях вашего сайта. Эти средства отладки предназначены для локального тестирования и промежуточной установки, а не для живых сайтов.

Другие инструменты разработчика WordPress

В дополнение к WP_DEBUG, следующие плагины и наборы данных модульного тестирования являются важной частью вашего набора инструментов разработки и помогают вам разрабатывать лучшие темы WordPress.

Тестовые данные

Тестовые данные элментов темы WordPress.org

WordPress.org Theme Unit Test Data — это XML-файл, содержащий фиктивные тестовые данные, которые вы можете загрузить, чтобы проверить, как темы работают с различными типами и макетами контента.

Тестовые данные элментов темы WordPress.com

WordPress.com Theme Unit Test Data — это фиктивные тестовые данные, которые вы можете загрузить в установку WordPress для тестирования вашей темы, включая специфические для WordPress.com функции.

Плагины

Debug Bar (плагин WordPress)

Debug Bar добавляет админскую панель в интерфейс администратора WordPress, предоставляя централизованный инструмент для отладки.

Query Monitor (плагин WordPress)

Query Monitor позволяет отлаживать запросы к базе данных, запросы к API и AJAX, вызываемые для генерации страниц темы и функционала темы.

Log Deprecated Notices (плагин WordPress)

Log Deprecated Notices журналирует некорректное использования функций и использование устаревший файлов и функций в вашей теме WordPress.

Monster Widgets (плагин WordPress)

Monster Widget косолидирует базовые виджеты WordPress в единый виджет, позволяя вам тестировать функциональность стилей виджетов в вашей теме.

Developer (плагин WordPress)

Developer помогает оптимизировать вашу среду разработки, позволяя лёгкую установку инструментов и плагинов, которые помогают в решении проблем и проверке качества кода.

Theme-Check (плагин WordPress)

Theme-Check тестирует вашу тему на соответствие последним стандартам WordPress и лучшим практикам.

Руководство по обзору тем оформления WordPress

В дополнение к вышеперечисленным инструментам разработки, неплохо бы быть в курсе руководящих принципов команды по обзору тем WordPress.org для представления тем и рекомендаций по соблюдению стандартов кодирования WordPress. Эти рекомендации являются «золотым стандартом» для качественной разработки тем и полезны, даже если вы не планируете выпускать тему на WordPress.org для обещственности.

Дополнительные ресурсы

 

Примеры разработки тем оформления

 

Один из лучших способов понять стандарты кодирования тем — найти примеры других тем, которые были написаны с учетом этих стандартов.

Default “Twenty” themes

Упакованные в каждую версию WordPress начиная с версии 3.0 (и названную в честь года, в котором они были выпущены), темы по умолчанию являются одними из лучших для изучения того, как они создаются. Это потому, что они разработаны с учетом широкого использования и полностью соответствуют стандартам кодирования WordPress. Вы можете скачать и изучить файлы этих тем, а также использовать их в качестве примеров для ознакомления при обучении разработке собственных тем:

 

Тема оформления Underscores

В отличие от стандартных тем «Двадцатых», тема _s (или Underscores) предназначена для разработчиков, а не для конечных пользователей. Он предназначен для начальной темы оформления, которую вы можете использовать в качестве основы для ускорения своего развития. Она имеет ряд особенностей:

  • Хорошо прокомментированные шаблоны HTML5, включая шаблоны ошибок.
  • Простая кастомная реализация заголовка в inc/custom-header.php.
  • Простые теги шаблона в inc/template-tags чтобы шаблоны оставались организованными и для предотвращения дупликации кода.
  • Скрипты для улучшения навигации с клавиатурой—найдены в js/keyboard-image-navigation.js—а также навигация по маленькому экрану в js/navigation.js.
  • Пять примеров CSS макетов в /layouts а также стартовый CSS на которых вы можете построить ваш дизайн.
  • Код лицензирован под GPL.

Приведенные выше функции делают Underscores отличной темой для разработчика, желающего создать собственную тему. И даже если вы удалите дополнения, оставшаяся база — все еще отличный пример темы с хорошим кодом, разработанной с учетом стандартов и передового опыта.

Подробности обзора доступны на сайте Underscores.

Код Underscores можно найти на github.

 

Другие источники

Кроме того, все темы, опубликованные в каталоге тем, перед публикацией проверяются на соответствие стандартам. Изучение тем в каталоге — это отличный способ лучше понять, как работает разработка тем, и хороший способ получить вдохновение для вашей собственной темы.

 

Основы темы оформления

В данной главе вы начнёте учиться как разрабатывать темы оформления должным образом. Вы получите знания об анатомии темы и ее частей. Вы начнете с понимания структурных элементов темы, рассматривая файлы тем и типы публикаций. Затем вы узнаете, как сохранить ваши файлы организованными в рамках вашей темы.

Вы также рассмотрите на Цикл, который отвечает за извлечение контента из базы данных WordPress.

В заключение, вы узнаете больше о добавлении функций в свою тему, использовании функций темы, включая CSS и JavaScript, использовании условныех тегов для отображения только нужного контента, а также о работе с таксономиями по умолчанию и создавая свои собственные.

Файлы шаблона

Файлы шаблонов используются во всех темах WordPress, но сначала давайте узнаем о терминологии.

Терминология шаблонов

Термин “шаблон” используется при работе с темами оформления WordPress в нескольких случаях:

  • Файлы шаблонов, существующие внутри темы и отвечающие за то как отображается сайт.
  • Шаблоны страниц —  это те, которые применяются только к страницам, чтобы изменить их внешний вид. Шаблон страницы может быть применен к отдельной странице, разделу страницы или классу страниц.
  • Тэги шаблона это встроенные функции WordPress, которые вы можете использовать внутри файла шаблона для извлечения и отображения данных (такие как the_title() и the_content()).
  • Иерархия шаблона логика WordPress, используемая для того, чтобы решить, какие файлы шаблона темы использовать в зависимости от запрошенного содержимого.

Файлы шаблона

Темы WordPress состоят из файлов шаблонов. Это файлы PHP, которые содержат смесь HTML, тегов шаблонов и кода PHP.

Когда вы создаете свою тему, вы будете использовать файлы шаблонов, чтобы влиять на вёрстку и дизайн различных частей вашего сайта. Например, вы можете использовать шаблон header.php для создания заголовка или шаблон comments.php для добавления комментариев.

Когда кто-то посещает страницу на вашем сайте, WordPress загружает шаблон на основе запроса. Тип содержимого, отображаемого в файле шаблона, определяется типом публикации, связанным с файлом шаблона. Иерархия шаблонов описывает, какой файл шаблона будет загружен WordPress, в зависимости от типа запроса и наличия шаблона в теме. Затем сервер выполняет код PHP в шаблоне и возвращает HTML посетителю.

Самый важный файл шаблона — это index.php, который является универсальным шаблоном, если в иерархии шаблонов нет более конкретного шаблона. Хотя теме нужен только шаблон index.php, обычно темы включают множество шаблонов для отображения различных типов контента и контекстов.

Частичные шаблоны

Частичный шаблон — это кусок шаблона, который подключается как часть другого шаблона, например такой как шапка сайта. Частичные шаблоны могут встраиваться в несколько шаблонов, упрощая создание темы оформления. Наиболее распространённые частичные шаблоны включают:

  • header.php для генерации шапки сайта
  • footer.php для генерации подвала
  • sidebar.php для генерации боковой панели

Хотя приведенные выше файлы шаблонов являются особым случаем в WordPress и применяются только к одной части страницы, вы можете создать любое количество частичных шаблонов и включить их в другие файлы шаблонов.

Наиболее распространённые файлы шаблонов

Ниже дан список базовых шаблонов темы оформления и файлов, которые распознает WordPress.

index.php
Основной файл шаблона. Он обязательно должен быть во всех темах.
style.css
Основной файл со стилями. Он обязательно должен быть во всех темах и содержит информацию о вашей теме.

rtl.css
Файл стилей справа налево. Он автоматически подключается, если язык сайта имеет направление написания справа налево.
comments.php
Шаблон комментариев.
front-page.php
Шаблон главной страницы, который, если существует, всегда используется главной страницей сайта, независимо от настроек в Админка > Настройки > Чтение.
home.php
Шаблон домашней страницы по умолчанию является шаблоном главной страницы. Если вы не указали WordPress, чтобы он использовал статическую главную страницу, то данный шаблон используется для отображения последних публикаций.
header.php
Файл шаблона шапки обычно содержит тип документа вашего сайта, мета-информацию, ссылки на стили и скрипты, а также другие данные.
singular.php
Данный шаблон используется для записей, если не найден файл шаблонаsingle.php или для страниц, если не найден файл шаблона page.php. Если singular.php тоже не найден, используется файл шаблона index.php.
single.php
Шаблон вывода одиночной записи, который используется, когда посетитель сайта просматривает одиночную запись.
single-{тип-публикации}.php
Шаблон одиночной записи, который используется, когда посетитель сайта просматривает одиночную публикацию, специально указанного типа. Например, single-book.php должен быть использован для отображения одиночных публикаций специального типа book. Если шаблон одиночной публикации специального типа не существует, то будет использован файл шаблона index.php.
archive-{тип-записи}.php
Шаблон одиночной архивной публикации, который используется, когда посетитель сайта просматривает одиночную архивную публикацию, специально указанного типа. Например, archive-books.phpдолжен быть использован для отображения одиночных архивных публикаций специального типа book. Если шаблонarchive-{post-type}.php не существует, то будет использован файл шаблонarchive.php.
page.php
Данный шаблон используется отображения отдельных страниц, которые являются встроенным шаблоном.
page-{slug}.php
Данный шаблон используется, для отображения специально указанной страницы, например, такой как страница со слагом “about” (page-about.php).
category.php
Данный шаблон используется для просмотра публикаций в категории.
tag.php
Данный шаблон используется для просмотра публикаций по тегу.
taxonomy.php
Данный шаблон используется при просмотре терминов в кастомной таксономии.
author.php
Данный шаблон используется при просмотре страницы автора.
date.php
Шаблон даты/времени, который используется, когда публикаия запрашивает дату или время. Например, страницы сгенерированы с данными слагами:
http://example.com/blog/2014/
http://example.com/blog/2014/05/
http://example.com/blog/2014/05/26/
archive.php
Данный шаблон используется, когда посетитель сайта запрашивает записи по категории, автору или дате. Обратите внимание: данный шаблон будет перекрыт, если есть более подходящие файлы шаблонов, такие как category.php, author.phpи date.php.
search.php
Это шаблон отображения результатов поиска.
attachment.php
Этот шаблон используется для просмотра одиночных прикреплений, таких как изображение, pdf или другие медиа-файлы.
image.php
Это специальная версия шаблона attachment.php, которая используется для просмотра одиночного прикреплённого изображения. Если не существует, WordPress будет использовать файл шаблона attachment.php instea.
404.php
Данный шаблон используется, когда WordPress не может найти запись, страницу или другие публикации, которые затребовал пользователь.

 

Использование файлов шаблонов

Вмест с шаблонами WordPress, вы можете использовать для динамического отображения информации Теги шаблонов, включая другие файлы шаблонов или напротив кастомизируя ваш сайт.

Например, в вашем index.phpвы можете включить в итоговую генерируемую страниц другие файлы:

  • Чтобы подключить шапку, используйте get_header()
  • Чтобы подключить боковую панель, используйте get_sidebar()
  • Чтобы подключить подвал, используйте get_footer()
  • Чтобы подключить форму поиска, используйте get_search_form()
  • Чтобы подключить кастомные файлы темы, используйте get_template_part()

Вот пример тегов шаблонов WordPress чтобы подключить специальные шаблоны к вашей странице:

1
2
3
<?php get_sidebar(); ?>
<?php get_template_part( 'featured-content' ); ?>
<?php get_footer(); ?>

Это полный шаблон, построенный на Тегах Шаблонов, в который вы можете погрузиться, чтобы узнать о них всё.

Больше информации о связывании компонентов шаблонов можно найти в разделе Связывание файлов темы и каталогов.

 

Главный файл стилей (style.css)

 

Файл style.css является для каждой темы WordPress файлом стилей (CSS). Он управляет представлением (внешним видом и вёрсткой) страниц сайта.

Местоположение

Чтобы WordPress распознал набор файлов шаблонов темы в качестве допустимой темы оформления, файл style.css должен находиться в корневом каталоге вашей темы, а не в подкаталоге.

Более подробное объяснение о том, как включить файл style.css в тему, см. В разделе «Таблицы стилей» в Сценариях и стилях.

Базовая структура

WordPress uses the header comment section of a style.css to display information about the theme in the Appearance (Themes) dashboard panel.

WordPress использует раздел комментариев в начале файла style.css для отображения информации о теме в при выборе пунка «Внешний вид» («Темы») в панели администратора.

Пример

Вот пример начала файла style.css.

/*
Theme Name: Twenty Seventeen
Theme URI: https://wordpress.org/themes/twentyseventeen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Seventeen brings your site to life with immersive featured images and subtle animations. With a focus on business sites, it features multiple sections on the front page as well as widgets, navigation and social menus, a logo, and more. Personalize its asymmetrical grid with a custom color scheme and showcase your multimedia content with post formats. Our default theme for 2017 works great in many languages, for any abilities, and on any device.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: twentyseventeen
Tags: one-column, two-columns, right-sidebar, flexible-header, accessibility-ready, custom-colors, custom-header, custom-menu, custom-logo, editor-style, featured-images, footer-widgets, post-formats, rtl-language-support, sticky-post, theme-options, threaded-comments, translation-ready
This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/

Пункты отмеченные (*) являются необходимыми для темы оформления в репозитории тем WordPress.

Обратите внимание: Репозиторий тем WordPress использует номер после слова “Version” в файле, чтобы определить, доступна ли для темы более новая версия.

  • Theme Name (*): Имя (название) данной темы.
  • Theme URI: URL публичной страницы, где пользователи могут найти больше информации о данной теме.
  • Author (*): Имя автора или название организации разработчика темы. Рекомендуется использовать в качестве автора имя пользователя с сайта wordpress.org.
  • Author URI: URL автора или организации.
  • Description (*): Краткое описание темы.
  • Version (*): Версия, в формате X.X или X.X.X.
  • License (*): Лицензия темы.
  • License URI (*): URL лицензии темы.
  • Text Domain (*): Строка используемая в качестве textdomain при переводе.
  • Tags: Слова или фразы, которые позволят пользователям найти данную тему с использованием фильтра по тегам. Полный список тегов можно найти на странице Руководства по обзору тем.
  • Domain Path: Используется для того, чтобы WordPress знал, где найти перевод, когда тема отключена. По умолчанию/languages.

После обязательной секции с вышеперечисленными полями, style.css может содержать всё, что содержится в любом CSS файле.

Style.css для дочерней темы

Если ваша тема является дочерней, в начальной секции style.css обязательно должно присутствовать поле Template, которое содержит имя родительского шаблона.

/*
Theme Name: My Child Theme
Template: Twenty Seventeen
*/

Больше информации о создании дочерних тем можно найти на странице Дочерние темы.

Типы публикаций

В WordPress есть много разных типов контента. Эти типы контента обычно описываются как Типы Публикаций, что может немного сбивать с толку, поскольку относится ко всем различным типам контента в WordPress. Например, запись — это определенный тип публикации, как и страница.

От переводчика: Русскоязычные пользователи запутываются вдвойне. Потому что так сложилось, что слово «Post» перевели как «Запись», но «Post» это также и публикация (в зависимости от контекста, который надо ещё понять) и соответственно когда пишут «Post Types» имеется в виду «Типы публикаций», а не «Типы записей».

Внутри все Типы Публикаций хранятся в одном и том же месте — в таблице базы данных wp_posts — но различаются по столбцу базы данных, называемому post_type.

В дополнение к стандартным Типам Публикаций вы также можете создавать собственные Типы.

На странице Файлы шаблонов кратко упоминается, что разные Типы Публикаций отображаются в разных файлах шаблонов. Поскольку основная цель файла шаблона состоит в том, чтобы отображать контент определенным образом, цель Типов Публикаций состоит в том, чтобы классифицировать тип контента, с которым вы имеете дело. Вообще говоря, определенные Типы Публикаций связаны с определенными файлами шаблонов.

Типы публикаций по умолчанию

Существует пять Типов Публикаций по умолчанию, которые доступны пользователям и которые создаются в процессе установки WordPress:

  • Запись (Тип публикации: ‘post’)
  • Страница (Тип публикации: ‘page’)
  • Прикрепление (Тип публикации: ‘attachment’)
  • Ревизия (Тип публикации: ‘revision’)
  • Меню навигации (Тип публикации: ‘nav_menu_item’)

Указанные выше типы публикаций могут быть изменены и удалены с помощью какого-либо плагина или темы, но удалять встроенные функции для широко распространяемой темы или плагина не рекомендуется.

Наиболее распространенными типами публикаций, с которыми вы будете взаимодействовать как разработчик тем, являются Запись, Страница, Прикрепление и кастомные Типы Публикаций. Данное руководство выходит за рамки описания Типов Публикаций Ревизия и Меню Навигации. Тем не менее, важно отметить, что вы будете взаимодействовать и создавать функциональность разных Меню Навигации, что будет подробно описано далее в этом руководстве.

Запись

Записи используются в блогах. Они:

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

Вот файлы шаблонов, которые отображают тип публикации Запись:

  • single.php и single-post.php
  • category.php и все итерации данного файла
  • tag.php и все итерации данного файла
  • taxonomy.php и все итерации данного файла
  • archive.php и все итерации данного файла
  • author.php и все итерации данного файла
  • date.php и все итерации данного файла
  • search.php
  • home.php
  • index.php

В дополнении, разработчики темы могут отображать тип публикации Запись в шаблоне front-page.php если они считают это необходимым.

Прочите доп. информацию о файлах Шаблонов Записей.

Страница

Страницы — это статический Тип Публикаций, выходящий за рамки обычного блога и ленты новостей. Имеют следующие особенности:

  • не зависят от времени и не содержат отметок времени
  • не организовываются по категориям и/или тегам таксономий
  • могут иметь шбалоны страниц, применяемых к ним
  • могут быть организованы в иерархическую структуру — т.е. страницы могут быть родителями или потомками для других страниц

Файлы шаблонов, которые отображают тип публикации Страница:

  • page.php и все итерации данного файла
  • $custom.php и все итерации данного файла
  • front-page.php
  • search.php
  • index.php

Прочтите доп. информацию о Файлах Шаблонов Страниц.

Прикрепления

Прикрепления обычно используются для показа изображений или других медиа-файлов в содержимом, а также могут быть использованы как ссылки для подходящих файлов. Особенности этого типа публикации:

  • содержит информацию (такую как имя или описание) о файлах, закаченных через систему закачки медиа
  • для изображений, включает информацию о метаданных, сохраняемую в таблицу wp_postmeta (включая размер, миниатюру, местоположение и т.д.)

Файлы шаблона, который отображают публикации этого типа:

  • MIME_type.php
  • attachment.php
  • single-attachment.php
  • single.php
  • index.php

Прочтите доп. информацию о Файлах Шаблона Прикреплений.

Кастомные типы публикаций

Используя Кастомные Типы Публикаций вы можете создать свой собственный тип публикации. Не рекомендуется размещать эту функциональность в своей теме. Данный вид функциональности должен быть размещен / создан в плагине. Это обеспечит переносимость содержимого вашего контента, а также то, что при изменении темы содержимое, сохраненное в кастомных типах публикаций, не исчезнет.

Вы можете узнать больше, прочтя  создание кастомных типов публикаций в руководстве по разработки плагинов для WordPress.

Хотя вы, как правило, не будете разрабатывать пользовательские типы публикаций в своей теме, вы можете захотеть написать код для отображения кастомных типов публикаций, которые были созданы каким-либо плагином. Следующие шаблоны могут отображать пользовательские типы публикаций:

  • single-{post-type}.php
  • archive-{post-type}.php
  • search.php
  • index.php

Кроме того, разработчики тем могут отображать Пользовательские Типы Публикаций в любом файле шаблона, часто используя несколько циклов.

Прочтите доп. информацию о Шаблонах Кастомных Типов Публикаций.

Как организованы файлы темы оформления

Хотя темы WordPress технически требуют только двух файлов (index.php и style.css), они обычно состоят из множества файлов. Это означает, что они могут быстро дезорганизоваться! Этот раздел покажет вам, как сохранить ваши файлы организованными.

Примечание. Темы без header.php и footer.php, несомненно устарели с WordPress 3.0. Вашей теме также могут понадобится эти файлы.

Каталог темы и файловая структура

As mentioned previously, the default Twenty themes are some of the best examples of good theme development. For instance, here is how the Twenty Seventeen Theme organizes its file structure:

Как упоминалось ранее, темы Twenty по умолчанию являются одними из лучших примеров хорошей разработки тем. Например, вот как тема Двадцать Семнадцать организована файловая структура:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
assets (dir)
      - css (dir)
      - images (dir)
      - js (dir)
inc (dir)
template-parts (dir)
      - footer (dir)
      - header (dir)
      - navigation (dir)
      - page (dir)
      - post (dir)
404.php
archive.php
comments.php
footer.php
front-page.php
functions.php
header.php
index.php
page.php
README.txt
rtl.css
screenshot.png
search.php
searchform.php
sidebar.php
single.php
style.css

Видно, что файлы основного шаблона темы находятся в корневом каталоге, тогда как JavaScript, CSS, изображения помещаются в каталог ресурсов assets, части шаблона размещаются в соответствующем подкаталоге частей шаблона template-parts, а набор функций, связанных с основными функциями, размещается в каталоге inc.

В настоящее время, никаких подкаталогов веутри каталога темы WordPress не требуется. Однако WordPress по умолчанию распознает вышеупомянутые подкаталоги.

Обратите внимание: Файл style.css должен находиться в корневом каталоге темы, а не внутри подкаталога CSS.

Подкаталог languages

Рекомендуется интернационализировать вашу тему, чтобы она могла быть переведена на другие языки. Темы по умолчанию включают подкаталог languages, который содержит файл .pot для перевода и уже имеющиеся файлы с переводоами с раширением .mo. Хотя languages является именем по умолчанию для этого подкаталога, вы можете его изменить. Если вы это сделаете, вы должны обновить load_theme_textdomain ().

 

Иерархия шаблона

Как уже говорилось, файлы шаблонов — это модульные, многократно используемые файлы,  для генерации веб-страниц на вашем сайте WordPress. Некоторые файлы шаблонов (например, шаблон шапки и шаблон подвала) используются на всех страницах вашего сайта, в то время как другие используются только при определенных условиях.

В этой статье объясняется, как WordPress определяет, какие файлы шаблонов использовать на отдельных страницах. Если вы хотите кастомизировать существующую тему WordPress, это поможет вам решить, какой файл шаблона нужно отредактировать.

Совет: Для управления какие шаблоны будут загружены на отдельных страницах, вы можете также использовать Теги условий.

 

Файловая иерархия шаблона

Обзор

WordPress использует строку запроса, чтобы решить, какой шаблон или набор шаблонов следует использовать для отображения страницы. Строка запроса — это информация, которая содержится в ссылке на каждую часть вашего сайта. Она идет после начального знака вопроса и может содержать ряд параметров, разделенных амперсандами.

Проще говоря, WordPress просматривает иерархию шаблонов, пока не найдет соответствующий файл шаблона. Чтобы определить, какой файл шаблона использовать, WordPresss:

  1. Сопоставляет каждую строку запроса с типом запроса, чтобы решить, какая страница запрашивается (например, страница поиска, страница категории и т. Д.);
  2. Выбирает шаблон в порядке, определенном иерархией шаблонов;
  3. Ищет файлы шаблонов с конкретными именами в каталоге текущей темы и использует первый соответствующий файл шаблона, как указано в иерархии.

За исключением базового файла шаблона index.php вы можете выбрать, хотите ли вы реализовать конкретный файл шаблона или нет.

Если WordPress не может найти файл шаблона с соответствующим именем, он перейдет к следующему файлу в иерархии. Если WordPress не может найти подходящий файл шаблона, будет использован файл index.php темы.

Примеры

Если ваш блог, это например, http://example.com/blog/ и посетитель сайта кликает на ссылку страницы категорий, такую как http://example.com/blog/category/your-cat/, WordPress ищет для правильной генерации страницы, файл шаблона в текущем каталоге темы, который совпадает с ID категории. Если по шагам, то WordPress следует вот такой процедуре:

  1. Ищет файл шаблона в каталоге текущей темы, соответствующий слагу категории. Если, например, слаг категории это «unicorns», то WordPress ищет файл шаблона с имене category-unicorns.php.
  2. Если файл category-unicorns.php отсутствует, а ID категории равен 4, WordPress ищет файл шаблона с именем category-4.php.
  3. Если файл category-4.php отсутствует, WordPress ищет файл общего шаблона для категорий category.php.
  4. Если файл category.php не существует, WordPress будет искать файл общего шаблона архивных публикаций archive.php.
  5. Если файл archive.php также отсутствует, WordPress вернётся к главному файлу шаблона темы index.php.

Наглядный обзор

На следующей диаграмме показано, какие файлы шаблонов вызываются для создания страницы WordPress на основе иерархии шаблонов WordPress.

 

Вы также можете взаимодействовать с этой диаграммой.

 

Подробности иерархии шаблонов

Хотя иерархию шаблонов легче понять в виде диаграммы, далее описывается порядок, в котором файлы шаблонов вызываются WordPress для ряда типов запросов.

Отображение Домашней Страницы

По умолчанию, WordPress устанавливает домашнюю страницу вашего сайта для отображения последних сообщений в блоге. Эта страница называется индексом публикаций блога. Вы также можете настроить отображение сообщений в своем блоге на отдельной статической странице. Для отображения индекса публикаций блога используется файл шаблона home.php, независимо от того, используется ли он в качестве главной страницы или на отдельной статической странице. Если файл home.php не существует, WordPress будет использовать index.php.

  1. home.php
  2. index.php

Обратите внимание: если файл front-page.php существует, он будет перекрывать шаблон home.php.

Отображение Главной Страницы

Файл шаблона front-page.php используется для отображения главной страницы вашего сайта, независимо от того, отображается ли на главной странице индекс публикаций в блоге (упомянутый выше) или статическая страница. Шаблон главной страницы имеет приоритет над шаблоном индекса публикаций в блоге (home.php). Если файл front-page.php не существует, WordPress будет использовать файлы home.php или page.php в зависимости от настроек в меню «Настройки» → «Чтение». Если ни один из этих файлов не существует, он будет использовать файл index.php.

  1. front-page.php – используется как для значения “ваши последние записи” так и для значения “статическая страница” настройки главная страница отображает в разделе Настройки → Чтение.
  2. home.php – Если WordPress не находит front-page.php и для настройки главная страница отображает установлено значение “ваши последние записи”, то он ищет файл  шаблона home.php. В дополенение, WordPress будет искать этот файл, если в настройке отображение индекса сообщений блога установлено значение страница записей.
  3. page.php – если в настройке главная страница отображает установлено значение “главная страница”.
  4. index.php – если в настройке главная страница отображает установлено значение “ваши последние записи” , но файл шаблона home.php не существует или если установлено значение главная страница, но файл шбалона page.php не существует.

Как видите, существует множество правил, которым следует WordPress. Использование диаграммы выше — лучший способ определить, что будет отображать WordPress в каждом конкретном случае.

Отображение страницы Политики Конфиденциальности

Файл шаблонп privacy-policy.php используется для генерации страницы Политика Конфиденциальности на вашем сайте. Шаблона страницы Политики Конфиденциальности имеет приоритет перед шаблоном статических страниц (page.php) . Если файл privacy-policy.php не существует, WordPress будет использовать или файл шаблона page.php или файл шаблона singular.php в зависимости от их доступности. Если ни один из них не существует, то будет использван файл index.php.

  1. privacy-policy.php – Используется для страницы Политики Конфиденциальности, установленной в настройке Выберите вашу страницу политики конфиндециальности в разделе Настройки → Конфиденциальность.
  2. custom template file –  шаблон страницы назначаемый для данной страницы. См. get_page_templates().
  3. page-{slug}.php – Если слаг страницы имеет значение privacy, WordPress будет использовать файл шаблона page-privacy.php.
  4. page-{id}.php – Если ID страницы равен 6, WordPress будет спользовать файл шаблона page-6.php.
  5. page.php
  6. singular.php
  7. index.php

Одиночная запись

Шаблон одиночной записи используется для отображения одиночной записи блога. WordPress использует следующий путь:

  1. single-{post-type}-{slug}.php – (начиная с версии 4.4) Сперва, WordPress ищет шаблон для конкретной публикации. Например, если тип публикации post type это product и слаг публикации это dmc-12, WordPress будет искать шаблон single-product-dmc-12.php.
  2. single-{post-type}.php – Если тип публикации это product, WordPress будет искать шаблон single-product.php.
  3. single.php – Затем, если вышеописанное не найдено, WordPress ищет single.php.
  4. singular.php – Затем, если вышеописанное не найдено, ищет singular.php.
  5. index.php – И наконец, если ничего из вышеописанного не найдено, WordPress переходит к index.php.

Одиночная страница

The template file used to render a static page (page post-type). Note that unlike other post-types, page is special to WordPress and uses the following path:

  1. custom template file – The page template assigned to the page. See get_page_templates().
  2. page-{slug}.php – If the page slug is recent-news, WordPress will look to use page-recent-news.php.
  3. page-{id}.php – If the page ID is 6, WordPress will look to use page-6.php.
  4. page.php
  5. singular.php
  6. index.php

Категория

Rendering category archive index pages uses the following path in WordPress:

  1. category-{slug}.php – If the category’s slug is news, WordPress will look for category-news.php.
  2. category-{id}.php – If the category’s ID is 6, WordPress will look for category-6.php.
  3. category.php
  4. archive.php
  5. index.php

Тег

To display a tag archive index page, WordPress uses the following path:

  1. tag-{slug}.php – If the tag’s slug is sometag, WordPress will look for tag-sometag.php.
  2. tag-{id}.php – If the tag’s ID is 6, WordPress will look for tag-6.php.
  3. tag.php
  4. archive.php
  5. index.php

Кастомные таксономии

Custom taxonomies use a slightly different template file path:

  1. taxonomy-{taxonomy}-{term}.php – If the taxonomy is sometax, and taxonomy’s term is someterm, WordPress will look for taxonomy-sometax-someterm.php. In the case of post formats, the taxonomy is ‘post_format’ and the terms are ‘post-format-{format}. i.e. taxonomy-post_format-post-format-link.php for the link post format.
  2. taxonomy-{taxonomy}.php – If the taxonomy were sometax, WordPress would look for taxonomy-sometax.php.
  3. taxonomy.php
  4. archive.php
  5. index.php

Кастомные типы публикаций

Custom Post Types use the following path to render the appropriate archive index page.

  1. archive-{post_type}.php – If the post type is product, WordPress will look for archive-product.php.
  2. archive.php
  3. index.php

(For rendering a single post type template, refer to the single post display section above.)

Экран автора

Based on the above examples, rendering author archive index pages is fairly explanatory:

  1. author-{nicename}.php – If the author’s nice name is matt, WordPress will look for author-matt.php.
  2. author-{id}.php – If the author’s ID were 6, WordPress will look for author-6.php.
  3. author.php
  4. archive.php
  5. index.php

Дата

Date-based archive index pages are rendered as you would expect:

  1. date.php
  2. archive.php
  3. index.php

Результат поиска

Search results follow the same pattern as other template types:

  1. search.php
  2. index.php

404 (Не найдено)

Likewise, 404 template files are called in this order:

  1. 404.php
  2. index.php

Прикрепление

Rendering an attachment page (attachment post-type) uses the following path:

  1. {MIME-type}.php – can be any MIME type (For example: image.php, video.php, pdf.php). For text/plain, the following path is used (in order):
    1. text-plain.php
    2. plain.php
    3. text.php
  2. attachment.php
  3. single-attachment-{slug}.php – For example, if the attachment slug is holiday, WordPress would look for single-attachment-holiday.php.
  4. single-attachment.php
  5. single.php
  6. singular.php
  7. index.php

Встроенное

The embed template file is used to render a post which is being embedded. Since 4.5, WordPress uses the following path:

  1. embed-{post-type}-{post_format}.php – First, WordPress looks for a template for the specific post. For example, if its post type is post and it has the audio format, WordPress would look for embed-post-audio.php.
  2. embed-{post-type}.php – If the post type is product, WordPress would look for embed-product.php.
  3. embed.php – WordPress then falls back to embed.php.
  4. Finally, WordPress ultimately falls back to its own wp-includes/theme-compat/embed.php template.

Top ↑

Non-ASCII Character Handling Non-ASCII Character Handling

Since WordPress 4.7, any dynamic part of a template name which includes non-ASCII characters in its name actually supports both the un-encoded and the encoded form, in that order. You can choose which to use.

Here’s the page template hierarchy for a page named “Hello World ?” with an ID of 6:

  • page-hello-world-?.php
  • page-hello-world-%f0%9f%98%80.php
  • page-6.php
  • page.php
  • singular.php

The same behaviour applies to post slugs, term names, and author nicenames.

Top ↑

Filter Hierarchy Filter Hierarchy

The WordPress template system lets you filter the hierarchy. This means that you can insert and change things at specific points of the hierarchy. The filter (located in the get_query_template() function) uses this filter name: "{$type}_template" where $type is the template type.

Here is a list of all available filters in the template hierarchy:

  • embed_template
  • 404_template
  • search_template
  • frontpage_template
  • home_template
  • privacypolicy_template
  • taxonomy_template
  • attachment_template
  • single_template
  • page_template
  • singular_template
  • category_template
  • tag_template
  • author_template
  • date_template
  • archive_template
  • index_template

Top ↑

Example Example

For example, let’s take the default author hierarchy:

  • author-{nicename}.php
  • author-{id}.php
  • author.php

To add author-{role}.php before author.php, we can manipulate the actual hierarchy using the ‘author_template’ template type. This allows a request for /author/username where username has the role of editor to display using author-editor.php if present in the current themes directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function author_role_template( $templates = '' ) {
    $author = get_queried_object();
    $role = $author->roles[0];
    if ( ! is_array( $templates ) && ! empty( $templates ) ) {
        $templates = locate_template( array( "author-$role.php", $templates ), false );
    } elseif ( empty( $templates ) ) {
        $templates = locate_template( "author-$role.php", false );
    } else {
        $new_template = locate_template( array( "author-$role.php" ) );
        if ( ! empty( $new_template ) ) {
            array_unshift( $templates, $new_template );
        }
    }
    return $templates;
}
add_filter( 'author_template', 'author_role_template' );

Template Tags

Template tags are used within themes to retrieve content from your database. The content could be anything from a blog title to a complete sidebar. Template tags are the preferred method to pull content into your theme because:

  • they can print dynamic content;
  • they can be used in multiple theme files; and
  • they separate the theme into smaller, more understandable, sections.

What is a Template Tag? What is a Template Tag?

A template tag is simply a piece of code that tells WordPress to get something from the database. It is broken up into three components:

  • A PHP code tag
  • A WordPress function
  • Optional parameters

You can use a template tag to call another theme file or some information from the database.

For example, the template tag get_header() tells WordPress to get the header.php file and include it in the current theme file. Similarly, get_footer() tells WordPress to get the footer.php file.

There are also other kinds of template tags:

  • the_title() – tells WordPress to get the title of the page or post from the database and include it.
  • bloginfo( 'name' ) – tells WordPress to get the blog title out of the database and include it in the template file.

If you look closely at the last example, you will also see that there is a parameter between the parenthesis. Parameters let you do two things:

  1. ask for specific pieces of information and
  2. format the information in a certain way.

Parameters are covered extensively below, but it’s useful to be aware that you can send WordPress-specific instructions for how you want the data presented.

Top ↑

Why Use Template Tags Why Use Template Tags

By encapsulating all of the code for a particular chunk of content, template tags make it very easy to include various pieces of a template in a theme file and also to maintain the theme.

It is far easier to create one header.php file and have all of your theme templates like single.php, page.php, front-page.php, etc. reference that one theme file using get_header() than copying and pasting the code into each theme file. It also makes maintenance easier. Whenever you make a change in your header.php file, the change is automatically carried over into all of your other theme files.

Another reason to use template tags is to display dynamic data, i.e. data from the database. In your header, you could manually include the title tag, like so:

1
&lt;title>My Personal Website&lt;/title>

However, doing this means manually editing your theme any time you want to change the title of your website. Instead, it’s easier to include the bloginfo( 'name' ) template tag, which automatically fetch the site title from the database. Now, you can change the title of your site in WordPress, rather than having to hard code your theme templates.

Top ↑

How to Use Template Tags How to Use Template Tags

Using template tags is very simple. In any template file you can use a template tag by simply printing one line of php code to call the template tag. Printing the header.php file is as simple as:

1
get_header();

Parameters Parameters

Some template tags let you pass parameters. Parameters are extra pieces of information that determine what is retrieved from the database.

For example, the bloginfo() template tag allows you to give it a parameter telling WordPress the specific piece of information you want. To print the blog name, you just pass along the parameter “name,” like so:

1
bloginfo( 'name' );

To print the version of WordPress that the blog is running on, you would pass a parameter of “version”:

1
bloginfo( 'version' );

For each template tag, the parameters differ. A list of the parameters and what they can do can be found on specific template tag pages located throughout the code reference.

Top ↑

Using Template Tags Within the Loop Using Template Tags Within the Loop

Many template tags work within the WordPress Loop. This means that they are included in the template files as part of the php “loop” that generates the pages users see based upon the instructions inside of the loop.

The WordPress loop begins with:

1
2
3
if ( have_posts() ) :
    while ( have_posts() ) :
        the_post();

Template tags that work within the loop must be in the middle area, before the ending section of the loop below:

1
2
3
4
    endwhile;
else :
    _e( 'Sorry, no posts matched your criteria.', 'devhub' );
endif;

Some of template tags that need to be inside of the loop include

The main reason why some functions require the loop is because they require the global post object to be set.

If the template tag you want to use doesn’t have to be within the loop

then you can put it in any file you’d like, for instance in the sidebar, header, or footer template files.

These are functions that typically do not require the global post object.

Top ↑

See Also See Also

The Loop

The Loop is the default mechanism WordPress uses for outputting posts through a theme’s template files. How many posts are retrieved is determined by the number of posts to show per page defined in the Reading settings. Within the Loop, WordPress retrieves each post to be displayed on the current page and formats it according to your theme’s instructions.

The Loop extracts the data for each post from the WordPress database and inserts the appropriate information in place of each template tag. Any HTML or PHP code in The Loop will be processed for each post.

To put it simply, the Loop is true to its name: it loops through each post retrieved for the current page one at a time and performs the action specified in your theme.

You can use the Loop for a number of different things, for example to:

  • display post titles and excerpts on your blog’s homepage;
  • display the content and comments on a single post;
  • display the content on an individual page using template tags; and
  • display data from Custom Post Types and Custom Fields.

You can customize the Loop across your template files to display and manipulate different content.

The Loop in Detail The Loop in Detail

The basic loop is:

1
2
3
4
5
6
7
<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        // Display post content
    endwhile;
endif;
?>

This loop says that when there are posts, loop through and display the posts. Broken down into more detail:

  • The have_posts() function checks whether there are any posts.
  • If there are posts, a while loop continues to execute as long as the condition in the parenthesis is logically true. As long as have_posts() continues to be true, the loop will continue.

Using The Loop Using The Loop

The Loop should be placed in index.php, and in any other templates which are used to display post information. Because you do not want to duplicate your header over and over, the loop should always be placed after the call to get_header(). For example:

1
2
3
4
5
6
7
8
<?php
get_header();
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        // Display post content
    endwhile;
endif;
?>

In the above example, the end of the Loop is shown with an endwhile and endif. The Loop must always begin with the same if and while statements, as mentioned above and must end with the same end statements.

Any template tags that you wish to apply to all posts must exist between the beginning and ending statements.

Tip: You can include a custom 404 “not found” message that will be displayed if no posts matching the specified criteria are available. The message must be placed between the endwhile and endif statements, as seen in examples below.

An extremely simple index.php file would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
get_header();
 
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_content();
    endwhile;
else :
    _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
endif;
 
get_sidebar();
get_footer();
?>

Top ↑

What the Loop Can Display What the Loop Can Display

The Loop can display a number of different elements for each post. For example, some common template tags used in many themes are:

  • next_post_link() – a link to the post published chronologically after the current post
  • previous_post_link() – a link to the post published chronologically before the current post
  • the_category() – the category or categories associated with the post or page being viewed
  • the_author() – the author of the post or page
  • the_content() – the main content for a post or page
  • the_excerpt() – the first 55 words of a post’s main content followed by an ellipsis (…) or read more link that goes to the full post. You may also use the “Excerpt” field of a post to customize the length of a particular excerpt.
  • the_ID() – the ID for the post or page
  • the_meta() – the custom fields associated with the post or page
  • the_shortlink() – a link to the page or post using the url of the site and the ID of the post or page
  • the_tags() – the tag or tags associated with the post
  • the_title() – the title of the post or page
  • the_time() – the time or date for the post or page. This can be customized using standard php date function formatting.

You can also use conditional tags, such as:

  • is_home() – Returns true if the current page is the homepage
  • is_admin() – Returns true if inside Administration Screen, false otherwise
  • is_single() – Returns true if the page is currently displaying a single post
  • is_page() – Returns true if the page is currently displaying a single page
  • is_page_template() – Can be used to determine if a page is using a specific template, for example: is_page_template('about-page.php')
  • is_category() – Returns true if page or post has the specified category, for example: is_category('news')
  • is_tag() – Returns true if a page or post has the specified tag
  • is_author() – Returns true if inside author’s archive page
  • is_search() – Returns true if the current page is a search results page
  • is_404() – Returns true if the current page does not exist
  • has_excerpt() – Returns true if the post or page has an excerpt

Top ↑

Examples Examples

Let’s take a look at some examples of the Loop in action:

Top ↑

Basic Examples Basic Examples

Blog Archive Blog Archive

Most blogs have a blog archive page, which can show a number of things including the post title, thumbnail, and excerpt. The example below shows a simple loop that checks to see if there are any posts and, if there are, outputs each post’s title, thumbnail, and excerpt. If no posts exists, it displays the message in parentheses.

1
2
3
4
5
6
7
8
9
10
11
<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_title( '<h2>', '</h2>' );
        the_post_thumbnail();
        the_excerpt();
    endwhile;
else:
    _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
endif;
?>

Top ↑

Individual Post Individual Post

In WordPress, each post has its own page, which displays the relevant information for that post. Template tags allow you to customize which information you want to display.

In the example below, the loop outputs the post’s title and content. You could use this example in a post or page template file to display the most basic information about the post. You could also customize this template to add more data to the post, for example the category.

1
2
3
4
5
6
7
8
9
10
<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_title( '<h1>', '</h1>' );
        the_content();
    endwhile;
else:
    _e( 'Sorry, no pages matched your criteria.', 'textdomain' );
endif;
?>

Top ↑

Intermediate Examples Intermediate Examples

Top ↑

Style Posts from Some Categories Differently Style Posts from Some Categories Differently

The example below does a couple of things:

  • First, it displays each post with its title, time, author, content, and category, similar to the individual post example above.
  • Next, it makes it possible for posts with the category ID of “3” to be styled differently, utilizing the in_category() template tag.

Code comments in this example provide details throughout each stage of the loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
// Start the Loop.
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        /* * See if the current post is in category 3.
          * If it is, the div is given the CSS class "post-category-three".
          * Otherwise, the div is given the CSS class "post".
        */
        if ( in_category( 3 ) ) : ?>
        <div class="post-category-three">
        <?php else : ?>
        <div class="post">
        <?php endif;
 
            // Display the post's title.
            the_title( '<h2>', ';</h2>' );
 
            // Display a link to other posts by this posts author.
            printf( __( 'Posted by %s', 'textdomain' ), get_the_author_posts_link() );
 
            // Display the post's content in a div.
            ?>
            <div class="entry">
                <?php the_content() ?>
             </div>
     
            <?php
            // Display a comma separated list of the post's categories.
            _e( 'Posted in ', 'textdomain' ); the_category( ', ' );
 
        // closes the first div box with the class of "post" or "post-cat-three"
       ?>
       </div>
 
    <?php
    // Stop the Loop, but allow for a "if not posts" situation
    endwhile;
 
else :
    /*
      * The very first "if" tested to see if there were any posts to
      * display. This "else" part tells what do if there weren't any.
     */
     _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
  
// Completely stop the Loop.
 endif;
?>

Top ↑

Multiple Loops Multiple Loops

In some situations, you may need to use more than one loop. For example you may want to display the titles of the posts in a table of content list at the top of the page and then display the content further down the page. Since the query isn’t being changed we simply need to rewind the loop when we need to loop through the posts for a second time. For that we will use the function rewind_posts().

Top ↑

Using rewind_posts() Using rewind_posts()

You can use rewind_posts() to loop through the same query a second time. This is useful if you want to display the same query twice in different locations on a page.

Here is an example of rewind_posts() in use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// Start the main loop
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_title();
    endwhile;
endif;
 
// Use rewind_posts() to use the query a second time.
rewind_posts();
 
// Start a new loop
while ( have_posts() ) : the_post();
    the_content();
endwhile;
?>

Top ↑

Creating secondary queries and loops Creating secondary queries and loops

Using two loops with the same query was relatively easy but not always what you will need. Instead, you will often want to create a secondary query to display different content on the template. For example, you might want to display two groups of posts on the same page, but do different things to each group. A common example of this, as shown below, is displaying a single post with a list of posts from the same category below the single post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
// The main query.
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_title();
        the_content();
    endwhile;
else :
    // When no posts are found, output this text.
    _e( 'Sorry, no posts matched your criteria.' );
endif;
wp_reset_postdata();                                                       
 
/*
 * The secondary query. Note that you can use any category name here. In our example,
 * we use "example-category".
 */
$secondary_query = new WP_Query( 'category_name=example-category' );       
 
// The second loop.
if ( $secondary_query->have_posts() )
    echo '<ul>';
    while ( $secondary_query->have_posts() ) : $secondary_query->the_post();
        the_title( '<li>', '</li>' );
     endwhile;
     echo '</ul>';
endif;
wp_reset_postdata();
?>

As you can see in the example above, we first display a regular loop. Then we define a new variable that uses WP_Query to query a specific category; in our case, we chose the example-category slug.

Note that the regular loop in the example above has one difference: it calls wp_reset_postdata() to reset the post data. Before you can use a second loop, you need to reset the post data. There are two ways to do this:

  1. By using the rewind_posts() function; or
  2. By creating new query objects.

Top ↑

Resetting multiple loops Resetting multiple loops

It’s important when using multiple loops in a template that you reset them. Not doing so can lead to unexpected results due to how data is stored and used within the global $post variable. There are three main ways to reset the loop depending on the way they are called.

Top ↑

Using wp_reset_postdata() Using wp_reset_postdata()

Use wp_reset_postdata() when you are running custom or multiple loops with WP_Query. This function restores the global $post variable to the current post in the main query. If you’re following best practices, this is the most common function you will use to reset loops.

To properly use this function, place the following code after any loops with WP_Query:

1
<?php wp_reset_postdata(); ?>

Here is an example of a loop using WP_Query that is reset with wp_reset_postdata().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
// Example argument that defines three posts per page.
$args = array( 'posts_per_page' => 3 );
 
// Variable to call WP_Query.
$the_query = new WP_Query( $args );
 
if ( $the_query->have_posts() ) :
    // Start the Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
        the_title();
        the_excerpt();
    // End the Loop
    endwhile;
else:
// If no posts match this query, output this text.
    _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
endif;
 
wp_reset_postdata();
?>

Top ↑

Using wp_reset_query() Using wp_reset_query()

Using wp_reset_query() restores the WP_Query and global $post data to the original main query. You MUST use this function to reset your loop if you use query_posts() within your loop. You can use it after custom loops with WP_Query because it actually calls wp_reset_postdata() when it runs. However, it’s best practice to use wp_reset_postdata() with any custom loops involving WP_Query.

Alert: query_posts() is not best practice and should be avoided if at all possible. Therefore, you shouldn’t have much use for wp_reset_query().

To properly use this function, place the following code after any loops with query_posts().

1
<?php wp_reset_query(); ?>

 

Theme Functions

The functions.php file is where you add unique features to your WordPress theme. It can be used to hook into the core functions of WordPress to make your theme more modular, extensible, and functional.

What is functions.php? What is functions.php?

The functions.php file behaves like a WordPress plugin, adding features and functionality to a WordPress site. You can use it to call WordPress functions and to define your own functions.

Note: The same result can be produced using either a plugin or functions.php. If you are creating new features that should be available no matter what the website looks like, it is best practice to put them in a plugin.

There are advantages and tradeoffs to either using a WordPress plugin or using functions.php.

A WordPress plugin:

  • requires specific, unique header text;
  • is stored in wp-content/plugins, usually in a subdirectory;
  • only executes on page load when activated;
  • applies to all themes; and
  • should have a single purpose – for example, offer search engine optimization features or help with backups.

Meanwhile, a functions.php file:

  • requires no unique header text;
  • is stored in theme’s subdirectory in wp-content/themes;
  • executes only when in the active theme’s directory;
  • applies only to that theme (if the theme is changed, the features can no longer be used); and
  • can have numerous blocks of code used for many different purposes.

Each theme has its own functions file, but only code in the active theme’s functions.php is actually run. If your theme already has a functions file, you can add code to it. If not, you can create a plain-text file named functions.php to add to your theme’s directory, as explained below.

A child theme can have its own functions.php file. Adding a function to the child functions file is a risk-free way to modify a parent theme. That way, when the parent theme is updated, you don’t have to worry about your newly added function disappearing.

Note: Although the child theme’s functions.php is loaded by WordPress right before the parent theme’s functions.php, it does not override it. The child theme’s functions.php can be used to augment or replace the parent theme’s functions. Similarly, functions.php is loaded after any plugin files have loaded.

With functions.php you can:

  • Use WordPress hooks. For example, with the excerpt_length filter you can change your post excerpt length (from default of 55 words).
  • Enable WordPress features with add_theme_support(). For example, turn on post thumbnails, post formats, and navigation menus.
  • Define functions you wish to reuse in multiple theme template files.

Warning: If a WordPress plugin calls the same function, or filter, as you do in your functions.php, the results can be unexpected, even causing your site to be disabled.

Top ↑

Examples Examples

Below are a number of examples that you can use in your functions.php file to support various features. Each of these examples are allowed in your theme if you choose to submit it to the WordPress.org theme directory.

Theme Setup Theme Setup

A number of theme features should be included within a “setup” function that runs initially when your theme is activated. As shown below, each of these features can be added to your functions.php file to activate recommended WordPress features.

Note: It’s important to namespace your functions with your theme name. All examples below use myfirsttheme_ as their namespace, which should be customized based on your theme name.

To create this initial function, start a new function entitled myfirsttheme_setup(), like so:

1
2
3
4
5
6
7
8
9
10
if ( ! function_exists( 'myfirsttheme_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features
*
*  It is important to set up these functions before the init hook so that none of these
*  features are lost.
*
*  @since MyFirstTheme 1.0
*/
function myfirsttheme_setup() {

Note: In the above example, the function myfirsttheme_setup is started but not closed out. Be sure to close out your functions

Automatic feed links enables post and comment RSS feeds by default. These feeds will be displayed in <head> automatically. They can be called using add_theme_support().

1
add_theme_support( 'automatic-feed-links' );

Top ↑

Custom navigation menus allow users to edit and customize menus in the Menus admin panel, giving users a drag-and-drop interface to edit the various menus in their theme.

You can set up multiple menus in functions.php. They can be added using register_nav_menus() and inserted into a theme using wp_nav_menu(), as discussed later in this handbook. If your theme will allow more than one menu, you should use an array. While some themes will not have custom navigation menus, it is recommended that you allow this feature for easy customization.

1
2
3
4
register_nav_menus( array(
    'primary'   => __( 'Primary Menu', 'myfirsttheme' ),
    'secondary' => __( 'Secondary Menu', 'myfirsttheme' )
) );

Each of the menus you define can be called later using wp_nav_menu() and using the name assigned (i.e. primary) as the theme_location parameter.

Top ↑

Load Text Domain Load Text Domain

Themes can be translated into multiple languages by making the strings in your theme available for translation. To do so, you must use load_theme_textdomain(). For more information on making your theme available for translation, read the internationalization section.

1
load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );

Top ↑

Post Thumbnails Post Thumbnails

Post thumbnails and featured images allow your users to choose an image to represent their post. Your theme can decide how to display them, depending on its design. For example, you may choose to display a post thumbnail with each post in an archive view. Or, you may want to use a large featured image on your homepage. While not every theme needs featured images, it’s recommended that you support post thumbnails and featured images.

1
add_theme_support( 'post-thumbnails' );

Top ↑

Post Formats Post Formats

Post formats allow users to format their posts in different ways. This is useful for allowing bloggers to choose different formats and templates based on the content of the post. add_theme_support() is also used for Post Formats. This is recommended.

1
add_theme_support( 'post-formats'array ( 'aside', 'gallery', 'quote', 'image', 'video' ) );

Learn more about post formats.

Top ↑

Initial Setup Example Initial Setup Example

Including all of the above features will give you a functions.php file like the one below. Code comments have been added for future clarity.

As shown at the bottom of this example, you must add the required add_action() statement to ensure the myfirsttheme_setup function is loaded.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
if ( ! function_exists( 'myfirsttheme_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which runs
 * before the init hook. The init hook is too late for some features, such as indicating
 * support post thumbnails.
 */
function myfirsttheme_setup() {
 
    /**
     * Make theme available for translation.
     * Translations can be placed in the /languages/ directory.
     */
    load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );
 
    /**
     * Add default posts and comments RSS feed links to <head>.
     */
    add_theme_support( 'automatic-feed-links' );
 
    /**
     * Enable support for post thumbnails and featured images.
     */
    add_theme_support( 'post-thumbnails' );
 
    /**
     * Add support for two custom navigation menus.
     */
    register_nav_menus( array(
        'primary'   => __( 'Primary Menu', 'myfirsttheme' ),
        'secondary' => __('Secondary Menu', 'myfirsttheme' )
    ) );
 
    /**
     * Enable support for the following post formats:
     * aside, gallery, quote, image, and video
     */
    add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) );
}
endif; // myfirsttheme_setup
add_action( 'after_setup_theme', 'myfirsttheme_setup' );

Top ↑

Content Width Content Width

A content width is added to your functions.php file to ensure that no content or assets break the container of the site. The content width sets the maximum allowed width for any content added to your site, including uploaded images. In the example below, the content area has a maximum width of 800 pixels. No content will be larger than that.

1
2
if ( ! isset ( $content_width) )
    $content_width = 800;

Top ↑

Other Features Other Features

There are other common features you can include in functions.php. Listed below are some of the most common features. Click through and learn more about each of these features.

(Expand this section based on new pages.)

  • Custom Headers
  • Sidebars (widget areas)
  • Custom Background (needs link)
  • Add Editor Styles (needs link)
  • HTML5 (needs link)
  • Title tag (needs link)

Top ↑

Your functions.php File Your functions.php File

If you choose to include all of the functions listed above, this is what your functions.php might look like. It has been commented with references to above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* MyFirstTheme's functions and definitions
*
* @package MyFirstTheme
* @since MyFirstTheme 1.0
*/
 
/**
* First, let's set the maximum content width based on the theme's design and stylesheet.
* This will limit the width of all uploaded images and embeds.
*/
if ( ! isset( $content_width ) )
$content_width = 800; /* pixels */
 
if ( ! function_exists( 'myfirsttheme_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which runs
* before the init hook. The init hook is too late for some features, such as indicating
* support post thumbnails.
*/
function myfirsttheme_setup() {
 
/**
* Make theme available for translation.
* Translations can be placed in the /languages/ directory.
*/
load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );
 
/**
* Add default posts and comments RSS feed links to <head>.
*/
add_theme_support( 'automatic-feed-links' );
 
/**
* Enable support for post thumbnails and featured images.
*/
add_theme_support( 'post-thumbnails' );
 
/**
* Add support for two custom navigation menus.
*/
register_nav_menus( array(
'primary'   => __( 'Primary Menu', 'myfirsttheme' ),
'secondary' => __('Secondary Menu', 'myfirsttheme' )
) );
 
/**
* Enable support for the following post formats:
* aside, gallery, quote, image, and video
*/
add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) );
}
endif; // myfirsttheme_setup
add_action( 'after_setup_theme', 'myfirsttheme_setup' );

 

Linking Theme Files & Directories

Linking to Core Theme Files Linking to Core Theme Files

As you’ve learned, WordPress themes are built from a number of different template files. At the very least this will usually include a sidebar.php, header.php and footer.php. These are called using Template Tags, for example:

You can create custom versions of these files can be called as well by naming the file sidebar-{your_custom_template}.php, header-{your_custom_template}.php and footer-{your_custom_template}.php. You can then use Template Tags with the custom template name as the only parameter, like this:

1
2
3
get_header( 'your_custom_template' );
get_footer( 'your_custom_template' );
get_sidebar( 'your_custom_template' );

WordPress creates pages by assembling various files. Aside from the standard files for the header, footer and sidebar, you can create custom template files and call them at any location in the page using get_template_part(). To create a custom template file in your theme give the file an appropriate name and use the same custom template system as with the header, sidebar and footer files:

1
slug-template.php

For example, if you would like to create a custom template to handle your post content you could create a template file called content.php and then add a specific content layout for product content by extending the file name to content-product.php. You would then load this template file in your theme like this:

1
get_template_part( 'content', 'product' );

If you want to add more organization to your templates, you can place them in their own directories within your theme directory. For example, suppose you add a couple more content templates for profiles and locations, and group them in their own directory called content-templates.

The theme hierarchy for your theme called my-theme might look like the following. style.css and page.php are included for context.

  • themes
  • my-theme
  • content-templates
  • content-location.php
  • content-product.php
  • content-profile.php
  • style.css

To include your content templates, prepend the directory names to the slug argument like this:

1
2
3
get_template_part( 'content-templates/content', 'location' );
get_template_part( 'content-templates/content', 'product' );
get_template_part( 'content-templates/content', 'profile' );

Top ↑

Linking to Theme Directories Linking to Theme Directories

To link to the theme’s directory, you can use the following function:

If you are not using a child theme, this function will return the full URI to your theme’s main folder. You can use this to reference sub-folders and files in your theme like this:

1
echo get_theme_file_uri( 'images/logo.png' );

If you are using a child theme then this function will return the URI of the file in your child theme if it exists. If the file cannot be found in your child theme, the function will return the URI of the file in the parent theme. This is particularly important to keep in mind when distributing a theme or in any other case where a child theme may or may not be active.

To access the path to a file in your theme’s directories, you can use the following function:

Like get_theme_file_uri(), this will access the path of the file in the child theme if it exists. If the file cannot be found in the child theme, the function will access the path to the file in the parent theme.

In a child theme, you can link to a file URI or path in the parent theme’s directories using the following functions:

As with  get_theme_file_uri(), you can reference sub-folders and files like this:

1
2
3
echo get_parent_theme_file_uri( 'images/logo.png' );
//or
echo get_parent_theme_file_path( 'images/logo.png' );

Take care when referencing files that may not be present, as these functions will return the URI or file path whether the file exists or not. If the file is missing, these functions will return a broken link.

Note: The functions get_theme_file_uri(), get_theme_file_path(), get_parent_theme_file_uri(), get_parent_theme_file_path() were introduced in WordPress 4.7.

For previous WordPress versions, use get_template_directory_uri(), get_template_directory(), get_stylesheet_directory_uri(), get_stylesheet_directory().

Take note that the newer 4.7 functions run the older functions anyway as part of the checking process so it makes sense to use the newer functions when possible.

Top ↑

Dynamic Linking in Templates Dynamic Linking in Templates

Regardless of your permalink settings, you can link to a page or post dynamically by referring to its unique numerical ID (seen in several pages in the admin interface) with

1
<a href="<?php echo get_permalink($ID); ?>">This is a link</a>

This is a convenient way to create page menus as you can later change page slugs without breaking links, as IDs will stay the same. However, this might increase database queries.

 

Including CSS & JavaScript

When you’re creating your theme, you may want to create additional stylesheets or JavaScript files. However, remember that a WordPress website will not just have your theme active, it will also be using many different plugins. So that everything works harmoniously, it’s important that theme and plugins load scripts and stylesheets using the standard WordPress method. This will ensure the site remains efficient and that there are no incompatibility issues.

Adding scripts and styles to WordPress is a fairly simple process.   Essentially, you will create a function that will enqueue all of your scripts and styles. When enqueuing a script or stylesheet, WordPress creates a handle and path to find your file and any dependencies it may have (like jQuery) and then you will use a hook that will insert your scripts and stylesheets.

Enqueuing Scripts and Styles Enqueuing Scripts and Styles

The proper way to add scripts and styles to your theme is to enqueue them in the functions.php files. The style.css file is required in all themes, but it may be necessary to add other files to extend the functionality of your theme.

Tip: WordPress includes a number of JavaScript files as part of the software package, including commonly used libraries such as jQuery. Before adding your own JavaScript, check to see if you can make use of an included library.

The basics are:

  1. Enqueue the script or style using wp_enqueue_script() or wp_enqueue_style()

Stylesheets Stylesheets

Your CSS stylesheets are used to customize the presentation of your theme. A stylesheet is also the file where information about your theme is stored. For this reason, the style.css file is required in every theme.

Rather then loading the stylesheet in your header.php file, you should load it in using wp_enqueue_style. In order to load your main stylesheet, you can enqueue it in functions.php

To enqueue style.css

1
wp_enqueue_style( 'style', get_stylesheet_uri() );

This will look for a stylesheet named “style” and load it.

The basic function for enqueuing a style is:

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

You can include these parameters:

  • $handle is simply the name of the stylesheet.
  • $src is where it is located. The rest of the parameters are optional.
  • $deps refers to whether or not this stylesheet is dependent on another stylesheet. If this is set, this stylesheet will not be loaded unless its dependent stylesheet is loaded first.
  • $ver sets the version number.
  • $media can specify which type of media to load this stylesheet in, such as ‘all’, ‘screen’, ‘print’ or ‘handheld.’

So if you wanted to load a stylesheet named “slider.css” in a folder named “CSS” in you theme’s root directory, you would use:

1
wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css',false,'1.1','all');

Top ↑

Scripts Scripts

Any additional JavaScript files required by a theme should be loaded using wp_enqueue_script. This ensures proper loading and caching, and allows the use conditional tags to target specific pages. These are optional.

wp_enqueue_script uses a similar syntax to wp_enqueue_style.

Enqueue your script:

1
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer);
  • $handle is the name for the script.
  • $src defines where the script is located.
  • $deps is an array that can handle any script that your new script depends on, such as jQuery.
  • $ver lets you list a version number.
  • $in_footer is a boolean parameter (true/false) that allows you to place your scripts in the footer of your HTML document rather then in the header, so that it does not delay the loading of the DOM tree.

Your enqueue function may look like this:

1
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true);

Top ↑

The Comment Reply Script The Comment Reply Script

WordPress comments have quite a bit of functionality in them right out of the box, including threaded comments and enhanced comment forms. In order for comments to work properly, they require some JavaScript. However, since there are certain options that need to be defined within this JavaScript, the comment-reply script should be added to every theme that uses comments.

The proper way to include comment reply is to use conditional tags to check if certain conditions exist, so that the script isn’t being loaded unnecessarily. For instance, you can only load scripts on single post pages using is_singular, and check to make sure that “Enable threaded comments” is selected by the user. So you can set up a function like:

1
2
3
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
    wp_enqueue_script( 'comment-reply' );
}

If comments are enabled by the user, and we are on a post page, then the comment reply script will be loaded. Otherwise, it will not.

Top ↑

Combining Enqueue Functions Combining Enqueue Functions

It is best to combine all enqueued scripts and styles into a single function, and then call them using the wp_enqueue_scripts action. This function and action should be located somewhere below the initial setup (performed above).

1
2
3
4
5
6
7
8
9
10
11
12
function add_theme_scripts() {
  wp_enqueue_style( 'style', get_stylesheet_uri() );
 
  wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css', array(), '1.1', 'all');
 
  wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true);
 
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
      wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );

Top ↑

Default Scripts Included and Registered by WordPress Default Scripts Included and Registered by WordPress

By default, WordPress includes many popular scripts commonly used by web developers, as well as the scripts used by WordPress itself. Some of them are listed in the table below:

Script Name Handle Needed Dependency *
Image Cropper Image cropper (not used in core, see jcrop)
Jcrop jcrop
SWFObject swfobject
SWFUpload swfupload
SWFUpload Degrade swfupload-degrade
SWFUpload Queue swfupload-queue
SWFUpload Handlers swfupload-handlers
jQuery jquery json2 (for AJAX calls)
jQuery Form jquery-form jquery
jQuery Color jquery-color jquery
jQuery Masonry jquery-masonry jquery
jQuery UI Core jquery-ui-core jquery
jQuery UI Widget jquery-ui-widget jquery
jQuery UI Mouse jquery-ui-mouse jquery
jQuery UI Accordion jquery-ui-accordion jquery
jQuery UI Autocomplete jquery-ui-autocomplete jquery
jQuery UI Slider jquery-ui-slider jquery
jQuery UI Progressbar jquery-ui-progressbar jquery
jQuery UI Tabs jquery-ui-tabs jquery
jQuery UI Sortable jquery-ui-sortable jquery
jQuery UI Draggable jquery-ui-draggable jquery
jQuery UI Droppable jquery-ui-droppable jquery
jQuery UI Selectable jquery-ui-selectable jquery
jQuery UI Position jquery-ui-position jquery
jQuery UI Datepicker jquery-ui-datepicker jquery
jQuery UI Tooltips jquery-ui-tooltip jquery
jQuery UI Resizable jquery-ui-resizable jquery
jQuery UI Dialog jquery-ui-dialog jquery
jQuery UI Button jquery-ui-button jquery
jQuery UI Effects jquery-effects-core jquery
jQuery UI Effects – Blind jquery-effects-blind jquery-effects-core
jQuery UI Effects – Bounce jquery-effects-bounce jquery-effects-core
jQuery UI Effects – Clip jquery-effects-clip jquery-effects-core
jQuery UI Effects – Drop jquery-effects-drop jquery-effects-core
jQuery UI Effects – Explode jquery-effects-explode jquery-effects-core
jQuery UI Effects – Fade jquery-effects-fade jquery-effects-core
jQuery UI Effects – Fold jquery-effects-fold jquery-effects-core
jQuery UI Effects – Highlight jquery-effects-highlight jquery-effects-core
jQuery UI Effects – Pulsate jquery-effects-pulsate jquery-effects-core
jQuery UI Effects – Scale jquery-effects-scale jquery-effects-core
jQuery UI Effects – Shake jquery-effects-shake jquery-effects-core
jQuery UI Effects – Slide jquery-effects-slide jquery-effects-core
jQuery UI Effects – Transfer jquery-effects-transfer jquery-effects-core
MediaElement.js (WP 3.6+) wp-mediaelement jquery
jQuery Schedule schedule jquery
jQuery Suggest suggest jquery
ThickBox thickbox
jQuery HoverIntent hoverIntent jquery
jQuery Hotkeys jquery-hotkeys jquery
Simple AJAX Code-Kit sack
QuickTags quicktags
Iris (Colour picker) iris jquery
Farbtastic (deprecated) farbtastic jquery
ColorPicker (deprecated) colorpicker jquery
Tiny MCE tiny_mce
Autosave autosave
WordPress AJAX Response wp-ajax-response
List Manipulation wp-lists
WP Common common
WP Editor editorremov
WP Editor Functions editor-functions
AJAX Cat ajaxcat
Admin Categories admin-categories
Admin Tags admin-tags
Admin custom fields admin-custom-fields
Password Strength Meter password-strength-meter
Admin Comments admin-comments
Admin Users admin-users
Admin Forms admin-forms
XFN xfn
Upload upload
PostBox postbox
Slug slug
Post post
Page page
Link link
Comment comment
Threaded Comments comment-reply
Admin Gallery admin-gallery
Media Upload media-upload
Admin widgets admin-widgets
Word Count word-count
Theme Preview theme-preview
JSON for JS json2
Plupload Core plupload
Plupload All Runtimes plupload-all
Plupload HTML4 plupload-html4
Plupload HTML5 plupload-html5
Plupload Flash plupload-flash
Plupload Silverlight plupload-silverlight
Underscore js underscore
Backbone js backbone
Removed from Core
Script Name Handle Removed Version Replaced With
Scriptaculous Root scriptaculous-root WP 3.5 Google Version
Scriptaculous Builder scriptaculous-builder WP 3.5 Google Version
Scriptaculous Drag & Drop scriptaculous-dragdrop WP 3.5 Google Version
Scriptaculous Effects scriptaculous-effects WP 3.5 Google Version
Scriptaculous Slider scriptaculous-slider WP 3.5 Google Version
Scriptaculous Sound scriptaculous-sound WP 3.5 Google Version
Scriptaculous Controls scriptaculous-controls WP 3.5 Google Version
Scriptaculous scriptaculous WP 3.5 Google Version
Prototype Framework prototype WP 3.5 Google Version

The list is far from complete. You can find a full list of included files in wp-includes/script-loader.php.

 

Conditional Tags

Conditional Tags can be used in your Template Files to alter the display of content depending on the conditions that the current page matches. They tell WordPress what code to display under specific conditions. Conditional Tags usually work with PHP if /else Conditional Statements.

The code begins by checking to see if a statement is true or false. If the statement is found to be true, the first set of code is executed. If it’s false, the first set of code is skipped, and the second set of code (after the else) is executed instead.

For example, you could ask if a user is logged in, and then provide a different greeting depending on the result.

1
2
3
4
5
if ( is_user_logged_in() ):
    echo 'Welcome, registered user!';
else:
    echo 'Welcome, visitor!';
endif;

Note the close relation these tags have to WordPress Template Hierarchy. [to be added, or removed?]

Where to Use Conditional Tags Where to Use Conditional Tags

For a Conditional Tag to modify your data, the information must already have been retrieved from your database, i.e. the query must have already run. If you use a Conditional Tag before there is data, there’ll be nothing to ask the if/else statement about.

It’s important to note that WordPress loads functions.php before the query is run, so if you simply include a Conditional Tag in that file, it won’t work.

Two ways to implement Conditional Tags:

  • place it in a Template File
  • create a function out of it in functions.php that hooks into an action/filter that triggers at a later point

Top ↑

The Conditions For The Conditions For

Listed below are the conditions under which each of the following conditional statements proves to be true. Tags which can accept parameters are noted.

The Main Page The Main Page

is_home()

This condition returns true when the main blog page is being displayed, usually in standard reverse chronological order. If your home page has been set to a Static Page instead, then this will only prove true on the page which you set as the “Posts page” in Settings > Reading.

Top ↑

The Front Page The Front Page

is_front_page()

This condition returns true when the front page of the site is displayed, regardless of whether it is set to show posts or a static page.

Returns true when:

  1. the main blog page is being displayed and
  2. the Settings > Reading -> Front page displays option is set to Your latest posts

OR

  1. when Settings > Reading -> Front page displays is set to A static page and
  2. the Front Page value is the current Page being displayed.

Top ↑

The Administration Panels The Administration Panels

is_admin()

This condition returns true when the Dashboard or the administration panels are being displayed.

Top ↑

A Single Post Page A Single Post Page

is_single()

Returns true when any single Post (or attachment, or custom Post Type) is being displayed. This condition returns false if you are on a page.

is_single( ’17’ )

is_single() can also check for certain posts by ID and other parameters. The above example proves true when Post 17 is being displayed as a single Post.

is_single( ‘Irish Stew’ )

Parameters include Post titles, as well. In this case, it proves true when the Post with title “Irish Stew” is being displayed as a single Post.

is_single( ‘beef-stew’ )

Proves true when the Post with Post Slug “beef-stew” is being displayed as a single Post.

is_single( array( 17, ‘beef-stew’, ‘Irish Stew’ ) )

Returns true when the single post being displayed is either post ID 17, or the post_name is “beef-stew”, or the post_title is “Irish Stew”.

is_single( array( 17, 19, 1, 11 ) )

Returns true when the single post being displayed is either post ID = 17, post ID = 19, post ID = 1 or post ID = 11.

is_single( array( ‘beef-stew’, ‘pea-soup’, ‘chilli’ ) )

Returns true when the single post being displayed is either the post_name “beef-stew”, post_name “pea-soup” or post_name “chilli”.

is_single( array( ‘Beef Stew’, ‘Pea Soup’, ‘Chilli’ ) )

Returns true when the single post being displayed is either the post_title is “Beef Stew”, post_title is “Pea Soup” or post_title is “Chilli”.

Note: This function does not distinguish between the post ID, post title, or post name. A post named “17” would be displayed if a post ID of 17 was requested. Presumably the same holds for a post with the slug “17”.

Top ↑

A Single Post, Page, or Attachment A Single Post, Page, or Attachment

is_singular()

Returns true for any is_single, is_page, and is_attachment. It does allow testing for post types.

Top ↑

A Sticky Post A Sticky Post

is_sticky()

Returns true if the “Stick this post to the front page” check box has been checked for the current post. In this example, no post ID argument is given, so the post ID for the Loop post is used.

is_sticky( ’17’ )
Returns true when Post 17 is considered a sticky post.

Top ↑

A Post Type A Post Type

get_post_type()

You can test to see if the current post is of a certain type by including get_post_type() in your conditional. It’s not really a conditional tag, but it returns the registered post type of the current post.

if ( ‘book’ == get_post_type() ) …

post_type_exists()

Returns true if a given post type is a registered post type. This does not test if a post is a certain post_type. Note: This function replaces a function called is_post_type which existed briefly in 3.0 development.

Top ↑

A Post Type is Hierarchical A Post Type is Hierarchical

is_post_type_hierarchical( $post_type )

Returns true if this $post_type has been set with hierarchical support when registered.

is_post_type_hierarchical( ‘book’ )

Returns true if the book post type was registered as having support for hierarchical.

Top ↑

 A Post Type Archive  A Post Type Archive

is_post_type_archive()

Returns true on any post type archive.

is_post_type_archive( $post_type )

Returns true if on a post type archive page that matches $post_type (can be a single post type or an array of post types).

To turn on post type archives, use ‘has_archive’ => true, when registering the post type.

Top ↑

A Comments Popup A Comments Popup

is_comments_popup()

When in Comments Popup window.

Top ↑

Any Page Containing Posts Any Page Containing Posts

comments_open()

When comments are allowed for the current Post being processed in the WordPress Loop.

pings_open()

When pings are allowed for the current Post being processed in the WordPress Loop.

Top ↑

A “PAGE” Page A “PAGE” Page

This section refers to WordPress Pages, not any generic webpage from your blog, or in other words to the built in post_type ‘page’.

is_page()

When any Page is being displayed.

is_page( ’42’ )

When Page 42 (ID) is being displayed.

is_page( ‘About Me And Joe’ )

When the Page with a post_title of “About Me And Joe” is being displayed.

is_page( ‘about-me’ )

When the Page with a post_name (slug) of “about-me” is being displayed.

is_page( array( 42, ‘about-me’, ‘About Me And Joe’ ) )

Returns true when the Pages displayed is either post ID = 42, or post_name is “about-me”, or post_title is “About Me And Joe”.

is_page( array( 42, 54, 6 ) )

Returns true when the Pages displayed is either post ID = 42, or post ID = 54, or post ID = 6.

Testing for Paginated Pages Testing for Paginated Pages

You can use this code to check whether you’re on the nth page in a Post or Page that has been divided into pages using the <!--nextpage-->
QuickTag. This can be useful, for example, if you wish to display meta-data only on the first page of a post divided into several pages.

Example 1
1
2
3
4
5
6
<?php
  $paged = $wp_query->get( 'page' );
  if ( ! $paged || $paged < 2 ) {
    // This is not a paginated page (or it's simply the first page of a paginated page/post)    } else {
    // This is a paginated page.
} ?>
Example 2
1
2
3
4
5
6
<?php $paged = get_query_var( 'page' ) ? get_query_var( 'page' ) : false;
    if ( $paged == false )  {
    // This is not a paginated page (or it's simply the first page of a paginated page/post) }  else  {
    // This is a paginated page.
    }
?>

Top ↑

Testing for Sub-Pages Testing for Sub-Pages

There is no is_subpage() function, but you can test this with a little code:

Snippet 1

1
2
3
4
5
6
7
<?php  global $post; // if outside the loop
   if ( is_page() &amp;&amp; $post->post_parent ) {
     // This is a subpage
   } else {
     // This is not a subpage
   }
?>

You can create your own is_subpage() function using the code in Snippet 2. Add it to your functions.php file. It tests for a parent page in the same way as Snippet 1, but will return the ID of the page parent if there is one, or false if there isn’t.

Snippet 2

1
2
3
4
5
6
7
8
9
10
function is_subpage() {
    global $post;                              // load details about this page
 
    if ( is_page() && $post->post_parent ) {   // test to see if the page has a parent
        return $post->post_parent;             // return the ID of the parent post
 
    } else {                                   // there is no parent so ...
        return false;                          // ... the answer to the question is false
    }
}

It is advisable to use a function like that in Snippet 2, rather than using the simple test like Snippet 1, if you plan to test for sub-pages frequently.

To test if the parent of a page is a specific page, for instance “About” (page id pid 2 by default), we can use the tests in Snippet 3. These tests check to see if we are looking at the page in question, as well as if we are looking at any child pages. This is useful for setting variables specific to different sections of a web site, so a different banner image, or a different heading.

Snippet 3

1
2
3
4
5
6
7
8
9
10
11
<?php if ( is_page( 'about' ) || '2' == $post->post_parent ) {
    // the page is "About", or the parent of the page is "About"
    $bannerimg = 'about.jpg';
} elseif ( is_page( 'learning' ) || '56' == $post->post_parent ) {
    $bannerimg = 'teaching.jpg';
} elseif ( is_page( 'admissions' ) || '15' == $post->post_parent ) {
    $bannerimg = 'admissions.jpg';
} else {
    $bannerimg = 'home.jpg'; // just in case we are at an unclassified page, perhaps the home page
}
?>

Snippet 4 is a function that allows you to carry out the tests above more easily. This function will return true if we are looking at the page in question (so “About”) or one of its sub pages (so a page with a parent with ID “2”).

Snippet 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function is_tree( $pid ) {      // $pid = The ID of the page we're looking for pages underneath
    global $post;               // load details about this page
 
    if ( is_page($pid) )
        return true;            // we're at the page or at a sub page
 
    $anc = get_post_ancestors( $post->ID );
    foreach ( $anc as $ancestor ) {
        if( is_page() && $ancestor == $pid ) {
            return true;
        }
    }
 
    return false;  // we aren't at the page, and the page is not an ancestor
}

Add Snippet 4 to your functions.php file, and call is_tree( ‘id’ ) to see if the current page is the page, or is a sub page of the page. In Snippet 3, is_tree( ‘2’ ) would replace “is_page( ‘about’ ) || ‘2’ == $post->post_parent” inside the first if tag.

Note that if you have more than one level of pages the parent page is the one directly above and not the one at the very top of the hierarchy.

Top ↑

Is a Page Template Is a Page Template

Allows you to determine whether or not you are in a page template or if a specific page template is being used.

is_page_template()

Is a Page Template being used?

is_page_template( ‘about.php’ )

Is Page Template ‘about’ being used? Note that unlike other conditionals, if you want to specify a particular Page Template, you need to use the filename, such as about.php or my_page_template.php.

Note: if the file is in a subdirectory you must include this as well. Meaning that this should be the filepath in relation to your theme as well as the filename, for example ‘page-templates/about.php’.

Top ↑

A Category Page A Category Page

is_category()

When a Category archive page is being displayed.

is_category( ‘9’ )

When the archive page for Category 9 is being displayed.

is_category( ‘Stinky Cheeses’ )

When the archive page for the Category with Name “Stinky Cheeses” is being displayed.

is_category( ‘blue-cheese’ )

When the archive page for the Category with Category Slug “blue-cheese” is being displayed.

is_category( array( 9, ‘blue-cheese’, ‘Stinky Cheeses’ ) )

Returns true when the category of posts being displayed is either term_ID 9, or slug “blue-cheese”, or name “Stinky Cheeses”.

in_category( ‘5’ )

Returns true if the current post is in the specified category id.

in_category( array( 1, 2, 3 ) )

Returns true if the current post is in either category 1, 2, or 3.

! in_category( array( 4, 5, 6 ) )

Returns true if the current post is NOT in either category 4, 5, or 6. Note the ! at the beginning.

Note: Be sure to check your spelling when testing. There’s a big difference between “is” or “in”.

See also is_archive() and Category Templates.

Top ↑

A Tag Page A Tag Page

is_tag()

When any Tag archive page is being displayed.

is_tag( ‘mild’ )

When the archive page for tag with the slug of ‘mild’ is being displayed.

is_tag( array( ‘sharp’, ‘mild’, ‘extreme’ ) )

Returns true when the tag archive being displayed has a slug of either “sharp”, “mild”, or “extreme”.

has_tag()

When the current post has a tag. Must be used inside The Loop.

has_tag( ‘mild’ )

When the current post has the tag ‘mild’.

has_tag( array( ‘sharp’, ‘mild’, ‘extreme’ ) )

When the current post has any of the tags in the array.

See also is_archive() and Tag Templates.

Top ↑

A Taxonomy Page A Taxonomy Page

is_tax()

When any Taxonomy archive page is being displayed.

is_tax( ‘flavor’ )

When a Taxonomy archive page for the flavor taxonomy is being displayed.

is_tax( ‘flavor’, ‘mild’)

When the archive page for the flavor taxonomy with the slug of ‘mild’ is being displayed.

is_tax( ‘flavor’, array( ‘sharp’, ‘mild’, ‘extreme’ ) )

Returns true when the flavor taxonomy archive being displayed has a slug of either “sharp”, “mild”, or “extreme”.

has_term()

Check if the current post has any of given terms. The first parameter should be an empty string. It expects a taxonomy slug/name as a second parameter.

has_term( ‘green’, ‘color’ )

When the current post has the term ‘green’ from taxonomy ‘color’.

has_term( array( ‘green’, ‘orange’, ‘blue’ ), ‘color’ )

When the current post has any of the terms in the array.

See also is_archive().

Top ↑

A Registered Taxonomy A Registered Taxonomy

taxonomy_exists()

When a particular taxonomy is registered via register_taxonomy(). Formerly is_taxonomy(), which was deprecated in Version 3.0

Top ↑

An Author Page An Author Page

is_author()

When any Author page is being displayed.

is_author( ‘4’ )

When the archive page for Author number (ID) 4 is being displayed.

is_author( ‘Vivian’ )

When the archive page for the Author with Nickname “Vivian” is being displayed.

is_author( ‘john-jones’ )

When the archive page for the Author with Nicename “john-jones” is being displayed.

is_author( array( 4, ‘john-jones’, ‘Vivian’ ) )

When the archive page for the author is either user ID 4, or user_nicename “john-jones”, or nickname “Vivian”.

See also is_archive() and Author Templates.

Top ↑

A Multi-author Site A Multi-author Site

is_multi_author()

When more than one author has published posts for a site. Available with Version 3.2.

Top ↑

A Date Page A Date Page

is_date()

When any date-based archive page is being displayed (i.e. a monthly, yearly, daily or time-based archive).

is_year()

When a yearly archive is being displayed.

is_month()

When a monthly archive is being displayed.

is_day()

When a daily archive is being displayed.

is_time()

When an hourly, “minutely”, or “secondly” archive is being displayed.

is_new_day()

If today is a new day according to post date. Should be used inside the loop.

Top ↑

Any Archive Page Any Archive Page

is_archive()

When any type of Archive page is being displayed. Category, Tag, Author and Date based pages are all types of Archives.

Top ↑

A Search Result Page A Search Result Page

is_search()

When a search result page archive is being displayed.

Top ↑

A 404 Not Found Page A 404 Not Found Page

is_404()

When a page displays after an “HTTP 404: Not Found” error occurs.

Top ↑

An Attachment An Attachment

is_attachment()

When an attachment document to a post or Page is being displayed. An attachment is an image or other file uploaded through the post editor’s upload utility. Attachments can be displayed on their own ‘page’ or template.

Top ↑

A Single Page, Single Post or Attachment A Single Page, Single Post or Attachment

is_singular()

When any of the following return true: is_single(), is_page() or is_attachment().

is_singular( ‘book’ )

True when viewing a post of the Custom Post Types book.

is_singular( array( ‘newspaper’, ‘book’ ) )

True when viewing a post of the Custom Post Types newspaper or book.

Top ↑

A Syndication A Syndication

is_feed()

When the site requested is a Syndication. This tag is not typically used by users; it is used internally by WordPress and is available for Plugin Developers.

Top ↑

A Trackback A Trackback

is_trackback()

When the site requested is WordPress’ hook into its Trackback engine. This tag is not typically used by users; it is used internally by WordPress and is available for Plugin Developers.

Top ↑

A Preview A Preview

is_preview()

When a single post being displayed is viewed in Draft mode.

Top ↑

Has An Excerpt Has An Excerpt

has_excerpt()

When the current post has an excerpt

has_excerpt( 42 )

When the post 42 (ID) has an excerpt.

1
2
3
4
5
6
7
<?php // Get $post if you're inside a function global $post;
   if ( empty( $post->post_excerpt ) ) {
    // This post has no excerpt
   } else {
    // This post has excerpt
  }
?>

Other use
When you need to hide the auto displayed excerpt and only display your post’s excerpts.

1
2
3
4
5
6
7
<?php
  if ( ! has_excerpt() ) {
      echo '';
  } else {
      the_excerpt();
  }
?>

Replace auto excerpt for a text or code.

1
2
3
<?php if ( ! has_excerpt() ) {
    // your text or code
} ?>

Top ↑

Has A Nav Menu Assigned Has A Nav Menu Assigned

has_nav_menu()

Whether a registered nav menu location has a menu assigned

Returns: assigned(true) or not(false)

Top ↑

Inside The Loop Inside The Loop

in_the_loop()

Check to see if you are “inside the loop”. Useful for plugin authors, this conditional returns as true when you are inside the loop.

Top ↑

Is Sidebar Active Is Sidebar Active

is_active_sidebar()

Check to see if a given sidebar is active (in use). Returns true if the sidebar (identified by name, id, or number) is in use, otherwise the function returns false.

Top ↑

Part of a Network (Multisite) Part of a Network (Multisite)

is_multisite()

Check to see whether the current site is in a WordPress MultiSite install.

Top ↑

Main Site (Multisite) Main Site (Multisite)

is_main_site()

Determines if a site is the main site in a network.

Top ↑

Admin of a Network (Multisite) Admin of a Network (Multisite)

is_super_admin()

Determines if a user is a network (super) admin.

Top ↑

An Active Plugin An Active Plugin

is_plugin_active()

Checks if a plugin is activated.

Top ↑

A Child Theme A Child Theme

is_child_theme()

Checks whether a child theme is in use.

Top ↑

Theme supports a feature Theme supports a feature

current_theme_supports()

Checks if various theme features exist.

Top ↑

Working Examples Working Examples

Here are working samples to demonstrate how to use these conditional tags.

Top ↑

Single Post Single Post

This example shows how to use is_single() to display something specific only when viewing a single post page:

1
2
3
4
5
if ( is_single() ) {
 
   echo 'This is just one of many fabulous entries in the ' . single_cat_title() . ' category!';
 
}

Another example of how to use Conditional Tags in the Loop. Choose to display content or excerpt in index.php when this is a display single post or the home page.

1
2
3
4
5
6
7
8
9
10
if ( is_home() || is_single() ) {
 
   the_content();
 
}
else {
 
   the_excerpt();
 
}

When you need display a code or element, in a place that is NOT the home page.

1
2
3
4
5
<?php if ( ! is_home() ) {
 
 // Insert your markup ...
 
} ?>

Top ↑

Check for Multiple Conditionals Check for Multiple Conditionals

You can use PHP operators to evaluate multiple conditionals in a single if statement.

This is handy if you need to check whether combinations of conditionals evaluate to true or false.

1
2
3
4
5
6
7
8
// Check to see if any of 2 conditionals are met
if ( is_single() || is_page() ) {
 // If it's a single post or a single page, do something special
}
 
if ( is_archive() && ! is_category( 'nachos' ) ) {
 // If it's an archive page for any category EXCEPT nachos, do something special
}
1
2
3
4
5
6
7
8
9
10
11
12
// Check to see if 3 conditionals are met
if ( $query->is_main_query() && is_post_type_archive( 'products' ) && ! is_admin() ) {
 
 // If it's the main query on a custom post type archive for Products
 // And if we're not in the WordPress admin, then do something special
 
}
if ( is_post_type_archive( 'movies' ) || is_tax( 'genre' ) || is_tax( 'actor' )  ) {
 // If it's a custom post type archive for Movies
 // Or it's a taxonomy archive for Genre
 // Or it's a taxonomy archive for Actor, do something special
}

Top ↑

Date Based Differences Date Based Differences

If someone browses our site by date, let’s distinguish posts in different years by using different colors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php // this starts The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h2>
 
<small><?php the_time('F jS, Y') ?> by <?php the_author() ?></small>
 
<?php
// are we showing a date-based archive?
if ( is_date() ) {
 if ( date( 'Y' ) != get_the_date( 'Y' ) ) {
 // this post was written in a previous year
 // so let's style the content using the "oldentry" class
 echo '<div class="oldentry">';
 } else {
 echo '<div class="entry">';
 }
} else {
 echo '<div class="entry">';
}
 
the_content( 'Read the rest of this entry »' );
?></div>

Top ↑

Variable Sidebar Content Variable Sidebar Content

This example will display different content in your sidebar based on what page the reader is currently viewing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div id="sidebar">
<?php // let's generate info appropriate to the page being displayed
if ( is_home() ) {
 // we're on the home page, so let's show a list of all top-level categories
    wp_list_categories( 'optionall=0&amp;sort_column=name&amp;list=1&amp;children=0' );
} elseif ( is_category() ) {
 // we're looking at a single category view, so let's show _all_ the categories
    wp_list_categories( 'optionall=1&amp;sort_column=name&amp;list=1&amp;children=1&amp;hierarchical=1' )
} elseif ( is_single() ) {
 // we're looking at a single page, so let's not show anything in the sidebar
} elseif ( is_page() ) {
 // we're looking at a static page. Which one?
 if ( is_page( 'About' ) ) {
 // our about page.
 echo "This is my about page!";
 } elseif ( is_page( 'Colophon' ) ) {
 echo "This is my colophon page, running on WordPress " . bloginfo( 'version' ) . "";
 } else {
 // catch-all for other pages
 echo "Vote for Pedro!";
 }
} else {
 // catch-all for everything else (archives, searches, 404s, etc)
 echo "Pedro offers you his protection.";
} // That's all, folks!
?>
</div>

Top ↑

Helpful 404 Page Helpful 404 Page

The Creating an Error 404 Page article [NEED Link to this?] has an example of using the PHP conditional function isset() in the Writing Friendly Messages section.

Top ↑

At times queries performed in other templates such as sidebar.php may corrupt certain conditional tags. For instance, in header.php a conditional tag works properly but doesn’t work in a theme’s footer.php. The trick is to put wp_reset_query before the conditional test in the footer. For example:

1
2
3
4
5
<?php wp_reset_query();
 if ( is_page( '2' ) ) {
  echo 'This is page 2!';
 }
?>

Top ↑

Conditional Tags Index Conditional Tags Index

Top ↑

Function Reference Function Reference

Categories, Tags, & Custom Taxonomies

Categories, tags, and taxonomies are all related and can be easily confused.  

We’ll use the example of building a theme for a recipe website to help break down categories, tags, and taxonomies. 

In our recipe website, the categories would be Breakfast, Lunch, Dinner, Appetizers, Soups, Salads, Sides, and Desserts. All recipes will fit within those categories, but users might want to search for something specific like chocolate desserts or ginger chicken dinners.  

Chocolate, ginger, and chicken are all examples of tags.  They are another level of specificity that provides meaning to the user.

Lastly, there are taxonomies. In reality, categories and tags are examples of default taxonomies which simply are a way to organize content.  Taxonomies are the method of classifying content and data in WordPress. When you use a taxonomy you’re grouping similar things together. The taxonomy refers to the sum of those groups. As with Post Types, there are a number of default taxonomies, and you can also create your own.

Recipes are normally organized by category and tag, but there are some other helpful ways to break the recipes down to be more user friendly.  For example, the recipe website might want an easy way to display recipes by cook time. A custom taxonomy of cook time with 0-30 min, 30-min to an hour, 1 to 2 hours, 2+ hours would be a great breakdown.  Additionally, cook method such as grill, oven, stove, refrigerator, etc would be another example of a custom taxonomy that would be relevant for the site.  There could also be a custom taxonomy for how spicy the recipe is and then a rating from 1-5 on spiciness.

Default Taxonomies Default Taxonomies

The default taxonomies in WordPress are:

  • categories: a hierarchical taxonomy that organizes content in the post Post Type
  • tags: a non-hierarchical taxonomy that organizes content in the post Post Type
  • post formats: a method for creating formats for your posts. You can learn more about these on the Post Formats page.

Terms Terms

Terms are items within your taxonomy. So, for example, if you have the Animal taxonomy you would have the terms, dogs, cats, and sheep. Terms can be created via the WordPress admin, or you can use the wp_insert_term() function.

Top ↑

Database Schema Database Schema

Taxonomies and terms are stored in the following database tables:

  • wp_terms – stores all of the terms
  • wp_term_taxonomy – places the term in a taxonomy
  • wp_term_relationships – relates the taxonomy to an object (for example, category to post)

taxonomy-schema

Top ↑

Templates Templates

WordPress offers several different hierarchies of templates for categories, tags, or custom taxonomies. More details on their structure and usage may be found on the Taxonomy Templates page.

Top ↑

Custom Taxonomies Custom Taxonomies

It is possible to create new taxonomies in WordPress. You may, for example, want to create an author taxonomy on a book review website, or an actor taxonomy on a film site. As with custom post type it is recommended that you put this functionality in a plugin. This ensures that when the user changes their website’s design, their content is preserved in the plugin.

You can read more about creating custom taxonomies in the Plugin Developer Handbook.

Установка WordPress

В данной статье подробно рассказывается о том как произвести установку WordPress на хостинг. Возможно, кому-то захочется или понадобится установить WordPress на свой компьютер с операционной системой Windows, так сказать локально. Это можно сделать с помощью Denwer и об этом будет рассказано в отдельной статье: установка WordPress на Denwer.

Читать далее «Установка WordPress»

О плагинах

Разговор в этой статье пойдёт о плагинах с точки зрения пользователя WordPress. О разработке плагинов разговор отдельный, а в этой статье я дам информацию, которая может стать крайне полезной для тех, кто не так давно установил WordPress и ещё не понимает некоторых тонкостей.

Читать далее «О плагинах»