- Небольшое руководство для новичков по условным тегам в WordPress
- Меняем на обратное!
- Давайте рассмотрим оператор ELSEIF
- Объединение условий
- Список популярных тегов WordPress
- Примеры использования условных тегов в WP
- Еще несколько примеров
- Для всего это существует отдельный плагин
- WordPress несколько условий if
- The Conditions For .
- The Main Page
- The Front Page
- The Blog Page
- The Administration Panels
- The Admin Bar
- A Single Post Page
- A Sticky Post
- A Post Type is Hierarchical
- A Post Type Archive
- A Comments Popup
- Any Page Containing Posts
- A PAGE Page
- Is a Page Template
- A Category Page
- A Tag Page
- A Taxonomy Page (and related)
- is_tax
- has_term
- term_exists
- is_taxonomy_hierarchical
- taxonomy_exists
- An Author Page
- A Multi-author Site
- A Date Page
- Any Archive Page
- A Search Result Page
- A 404 Not Found Page
- A Paged Page
- An Attachment
- Attachment Is Image
- A Local Attachment
- A Single Page, a Single Post, an Attachment or Any Other Custom Post Type
- Post Type Exists
- Is Main Query
- A New Day
- A Syndication
- A Trackback
- A Preview
- Has An Excerpt
- Has A Nav Menu Assigned
- Inside The Loop
- Is Dynamic SideBar
- Is Sidebar Active
- Is Widget Active
- Is Blog Installed
- Right To Left Reading
- Part of a Network (Multisite)
- Main Site (Multisite)
- Admin of a Network (Multisite)
- Is User Logged in
- Email Exists
- Username Exists
- An Active Plugin
- A Child Theme
- Theme supports a feature
- Has Post Thumbnail
- Script Is In use
- Is Previewed in the Customizer
- Working Examples
- Single Post
- Check for Multiple Conditionals
- Date-Based Differences
- Variable Sidebar Content
- Helpful 404 Page
- Dynamic Menu Highlighting
Небольшое руководство для новичков по условным тегам в WordPress
Условные теги – одна из особенностей, которую вы можете успешно использовать на своем WP-сайте, вне зависимости от того, являетесь ли вы асом в кодировании или же ваших знаний хватает только на установку плагина. Удивительно, что небольшой PHP-код способен преобразить ваш сайт на WordPress. Условные теги работают также и с BuddyPress.
Однако перед тем как начать пользоваться условными тегами, мы должны знать, что они из себя представляют. Если приводить простые сравнения, то условный тег – это вопрос, на который можно ответить «да» или «нет». Если вы решите их использовать, они возвратят вам либо истинный (true), либо ложный (false) ответ, и этот ответ будет определять, что произойдет дальше, основываясь на ваших инструкциях.
Вот простой пример того, как выглядит условный тег:
Что мы здесь делаем? Если условие, стоящее в круглых скобках, является истинным, то тогда выполняется то, что стоит в фигурных скобках.
К примеру, скажем:
То есть, если жарко, то тогда у вас должен быть под рукой холодный напиток. Полезный совет.
Меняем на обратное!
С другой стороны, если условие в круглых скобках не выполняется, то все остальное будет проигнорировано.
Мы можем сменить это на обратное, т.е. сделать так, чтобы, если условие неверно, то что-либо было выполнено. Для этого достаточно добавить символ «!» в начало нашего условия:
Поскольку условие в круглых скобках не является истинным, мы выполняем действия в фигурных скобках:
Вернемся назад к нашему примеру с напитком.
Читать это надо следующим образом: «если не жарко, то тогда у нас под рукой должен быть теплый напиток».
Таким образом, этот код прекрасно работает, если вы хотите сделать проверку одного условия и в зависимости от ответа выполнить какое-либо действие. Однако как быть, если нам нужно сделать разные действия в зависимости от истинности или ложности условия (или группы условий)?
Давайте рассмотрим оператор ELSEIF
Оператор ELSEIF во многом подобен оператору ELSE; он является расширением, которое позволяет вам проверять несколько условий и выполнять действие при соблюдении какого-либо из условий. Вот как это выглядит в теории:
Если первое условие верно, то выполняем указанные действия. Если первое условие не выполняется, переходим ко второму условию – если оно выполняется, совершаем приведенные действия. Вы можете добавить столько elseif-операторов, сколько захотите; пример с использованием нескольких elseif-операторов будет приведен далее.
Объединение условий
Прекрасно, что вы можете проверить условие и затем выполнить действие; однако как быть, если вы хотите проверить несколько условий? Поздоровайтесь с нашими новыми друзьями: AND и OR.
В качестве примера давайте выведем определенный текст в самом начале домашней страницы, но только если эта страница имеет >
Данную проверку можно немного изменить – мы можем сделать так, чтобы текст выводился при выполнении любого из этих двух условий:
Примечание: вместо AND мы можем использовать «&&», а вместо OR – «||».
Список популярных тегов WordPress
- is_page – применяет условие к определенной странице. Вы можете использовать ID, заголовок или слэг/название (пример: is_page(’3′) или is_page(‘Contact’)).
- is_home() – применяет условие к главной странице.
- is _category() – применяет условие к определенной рубрике (к примеру “Football”). Как и в случае с is_page(), мы можем использовать ID, заголовок или слэг/название рубрики (is_category(‘football’))
- is_single() – применяет условие к отдельным записям или прикреплениям.
- is_tag() – применяет условие к архивным страницам тегов.
- is_author() – применяет условие к архивным страницам авторов.
- is_archive() – применяет условие к архивным страницам.
- is_404() – применяет условие к странице 404.
- is_main_site – применяет условие к главному сайту в мультисайтовой сборке.
Примеры использования условных тегов в WP
Допустим, вы создаете сайт для газеты, и ее владельцы хотят выводить различные изображения в разных разделах сайта, чтобы посетители могли понять, какой именно раздел они в настоящее время читают. С помощью простого набора условных тегов вы можете легко достичь этого.
У нашей газеты есть четыре разных раздела, каждый из которых мы хотим идентифицировать:
- Стиль жизни (Lifestyle)
- Развлечения (Entertainment)
- Спорт (Sports)
- И подраздел в Спорте – Футбол (Football)
Такая вот небольшая газета.
Чтобы вывести изображение, которое будет отличаться в зависимости от раздела, мы должны немного поработать с кодом файла header.php нашей темы. Открываем редактор кода, находим строку:
Теперь нам понадобится удалить следующий код (он может отличаться в зависимости от выбранной темы: для данного примера я взял twentytwelve).
Удаляем следующую секцию, которая отвечает за вывод стандартного изображения в хэдере:
Код достаточно прост: мы задаем условия (определяем необходимую страницу), в зависимости от которых выводится то или иное изображение в хэдере.
Достаточно просто, и в то же время эффективно.
В принципе, ничего сложного в работе с условными тегами нет. Вот еще один небольшой пример, в котором мы вставляем текст Exclusive Article в начало одиночной записи:
Еще несколько примеров
Вот некоторые полезные примеры использования условных тегов.
1. Скрываем автоматически используемую цитату и отображаем цитату вашей записи:
2. Определяем, когда выводить цитату, а когда контент.
3. Проверяем, была ли загружена миниатюра; если нет, выводим стандартное изображение.
4. Если пользователь вошел под своим аккаунтом:
5. Различный хэдер или футер в зависимости от рубрики:
6. Проверяем, присвоен ли записи произвольный тип
Для всего это существует отдельный плагин
Что делать, если вы не желаете работать с кодом? Значит ли это, что вы не сможете воспользоваться условными тегами? Нет, поскольку мы знаем, что для этого есть плагин, который называется Widget Logic.
Этот плагин позволяет вам (среди прочего) выводить произвольный контент в вашем сайдбаре в зависимости от определенных параметров. Скажем, мы хотим, чтобы при просмотре архивов автора отображалась его краткая биография. Вместо того чтобы создавать новую страницу с произвольным сайдбаром, мы можем просто использовать плагин Widget Logic, который сделает большую часть работы за нас.
После установки плагина вы заметите, что у всех ваших виджетов теперь есть новая секция в самом низу, которая называется «Widget logic:». Эта новая секция позволяет определять, при каких условиях будет выводиться тот или иной виджет. Вам нужно просто добавить соответствующий условный тег в поле.
Возвращаясь обратно к нашему примеру – созданию биографии в сайдбаре для каждого автора, – я мог бы просто добавить отдельный текстовый виджет, содержащий биографию определенного автора, и указать для него тег is_author(ID). То же самое понадобится сделать для всех остальных авторов.
Плагин работает с любыми виджетами.
Это не единственный плагин, который позволяет обрабатывать различные условия. В хранилище WP есть много разных бесплатных плагинов, связанных с условными тегами.
WordPress несколько условий if
The Conditional Tags can be used in your Template files to change what content is displayed and how that content is displayed on a particular page depending on what conditions that page matches. For example, you might want to display a snippet of text above the series of posts, but only on the main page of your blog. With the is_home() Conditional Tag, that task is made easy.
Note the close relation these tags have to WordPress Template Hierarchy.
Warning: You can only use conditional query tags after the posts_selection action hook in WordPress (the wp action hook is the first one through which you can use these conditionals). For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.
However: if you have a reference to the query object (for example, from within the parse_query or pre_get_posts hooks), you can use the WP_Query conditional methods (eg: $query->is_search() )
The Conditions For .
All of the Conditional Tags test to see whether a certain condition is met, and then returns either TRUE or FALSE. The conditions under which various tags output TRUE is listed below. Those tags which can accept parameters are so noted.
The Main Page
The Front Page
The Blog Page
There is no conditional tag for the blog page. You have to use both is_home() and is_front_page() to detect this page, but those functions can be misused. In fact, a user can define a static page for the homepage, and another page to display the blog. This one will return true with is_home() function, even if it’s not the homepage. Here is what a user can define :
- a default homepage (with the latest posts)
- a static homepage and no blog page
- a static homepage and a blog page
When you use is_home() and is_front_page(), you have to use them in the right order to avoid bugs and to test every user configuration:
The Administration Panels
Attention: The wp-login.php page is not an admin page. To check if this page is displayed, use the admin global variable $pagenow.
The Admin Bar
Note : To display or not this bar, use show_admin_bar(), this function should be called immediately upon plugins_loaded or placed in the theme’s functions.php file.
A Single Post Page
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».
A Sticky Post
A Post Type is Hierarchical
A Post Type Archive
To turn on post type archives, use ‘has_archive’ => true, when registering the post type.
A Comments Popup
Any Page Containing Posts
A PAGE Page
This section refers to WordPress Pages, not any generic web page 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.
See also is_page() for more snippets, such as is_subpage, is_tree.
Note: There is no function to check if a page is a sub-page. We can get around the problem:
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: 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.
A Category Page
Note: Be sure to check your spelling when testing: «is» and «in» are significantly different.
A Tag Page
A Taxonomy Page (and related)
is_tax
has_term
term_exists
is_taxonomy_hierarchical
taxonomy_exists
An Author Page
A Multi-author Site
A Date Page
Any Archive Page
A Search Result Page
A 404 Not Found Page
A Paged Page
An Attachment
Attachment Is Image
A Local Attachment
A Single Page, a Single Post, an Attachment or Any Other Custom Post Type
Post Type Exists
Is Main Query
Example with the filter hook the_content
If, when WordPress tries to display the content of each post in the Loop or in a single post page, we are in the main query, and not admin side, we add some social buttons (for example).
Example with the action hook pre_get_posts
With pre_get_posts, this is not possible to call directly is_main_query, we should use $query given as a parameter.
A New Day
A Syndication
A Trackback
A Preview
Has An Excerpt
Has A Nav Menu Assigned
Inside The Loop
Is Dynamic SideBar
Is Sidebar Active
Note: To display a sidebar’s content, use dynamic_sidebar( $sidebar ).
Is Widget Active
Note : To be effective this function has to run after widgets have initialized, at action ‘init’ or later, see Action Reference.
Is Blog Installed
Note: The cache will be checked first. If you have a cache plugin, which saves the cache values, then this will work. If you use the default WordPress cache, and the database goes away, then you might have problems.
Right To Left Reading
Part of a Network (Multisite)
Main Site (Multisite)
Admin of a Network (Multisite)
Is User Logged in
Email Exists
Username Exists
An Active Plugin
A Child Theme
Theme supports a feature
Has Post Thumbnail
Script Is In use
This would check if the script named ‘fluidVids.js’ is enqueued. If it is not enqueued, the files are then registered and enqueued.
Is Previewed in the Customizer
Working Examples
Here are working samples to demonstrate how to use these conditional tags.
Single Post
This example shows how to use is_single() to display something specific only when viewing a single post page:
Add this custom function to your child themes functions.php file and modify the conditional tag to suit your needs.
You could also use:
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.
When you need display a code or element, in a place that is NOT the home page.
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.
Date-Based Differences
If someone browses our site by date, let’s distinguish posts in different years by using different colors:
Variable Sidebar Content
This example will display different content in your sidebar based on what page the reader is currently viewing.
Helpful 404 Page
The Creating an Error 404 Page article has an example of using the PHP conditional function isset() in the Writing Friendly Messages section.
Dynamic Menu Highlighting
The Dynamic Menu Highlighting article discusses how to use the conditional tags to enable highlighting of the current page in a menu.