- PHP if. else. elseif Statements
- PHP Conditional Statements
- PHP — The if Statement
- Syntax
- Example
- PHP — The if. else Statement
- Syntax
- Example
- PHP — The if. elseif. else Statement
- Syntax
- Example
- PHP — The switch Statement
- If this Page Show This Else Show This
- If this Page Show This Else Show This
- How to get the current file name using PHP script ?
- is_page() │ WP 1.5.0
- Возвращает
- Использование
- Примеры
- #1 Заметка про кириллицу и ярлык (слаг)
- #2 Функция в действии
- #3 Проверка находимся ли мы на дочерней странице у постоянной страницы
- #4 Проверка разделения страницы
- Заметки
- Список изменений
- Код is_page() is page WP 6.2.2
- Cвязанные функции
- Условные теги (типов страниц и запросов)
- Условные теги (все)
- Запросы
PHP if. else. elseif Statements
Conditional statements are used to perform different actions based on different conditions.
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
- if statement — executes some code if one condition is true
- if. else statement — executes some code if a condition is true and another code if that condition is false
- if. elseif. else statement — executes different codes for more than two conditions
- switch statement — selects one of many blocks of code to be executed
PHP — The if Statement
The if statement executes some code if one condition is true.
Syntax
Example
Output «Have a good day!» if the current time (HOUR) is less than 20:
PHP — The if. else Statement
The if. else statement executes some code if a condition is true and another code if that condition is false.
Syntax
if (condition) code to be executed if condition is true;
> else code to be executed if condition is false;
>
Example
Output «Have a good day!» if the current time is less than 20, and «Have a good night!» otherwise:
if ($t < "20") echo "Have a good day!";
> else echo «Have a good night!»;
>
?>
PHP — The if. elseif. else Statement
The if. elseif. else statement executes different codes for more than two conditions.
Syntax
if (condition) code to be executed if this condition is true;
> elseif (condition) code to be executed if first condition is false and this condition is true;
> else code to be executed if all conditions are false;
>
Example
Output «Have a good morning!» if the current time is less than 10, and «Have a good day!» if the current time is less than 20. Otherwise it will output «Have a good night!»:
if ($t < "10") echo "Have a good morning!";
> elseif ($t < "20") echo "Have a good day!";
> else echo «Have a good night!»;
>
?>
PHP — The switch Statement
The switch statement will be explained in the next chapter.
If this Page Show This Else Show This
Since we are using PHP, we can easily get the current file name or directory name of the current page by using $_SERVER[‘SCRIPT_NAME’]. Output To get only name of the current page opened at browser, see the below example: Output
If this Page Show This Else Show This
On all pages apart from the contact page, I want it to show the following in the inc-header.php include.
On the page contact.php , I want it to show:
This should be possible correct?
There is a global variable named $_SERVER[‘PHP_SELF’] that contains the name of your page currently requested. Combined with basename() this should work:
if( basename($_SERVER['PHP_SELF'], '.php') == 'contact' ) < // Contact page >else < // Some other page >
the quick and dirty solution is:
How to Redirect a Web Page with PHP, This short snippet will show you multiple ways of redirecting a web page with PHP. So, you can achieve redirection in PHP by following the guidelines below. Using …
How to get the current file name using PHP script ?
In this article, we will learn how to get the current file name using PHP.
Input : c:/xampp/htdocs/project/home.php Output : project/home.phpInput : c:/xampp/htdocs/project/abc.txt Output : project/abc.txt
Sometimes, we need to get the current file name with the directory name in which our page is stored for different purposes. Since we are using PHP, we can easily get the current file name or directory name of the current page by using $_SERVER[‘SCRIPT_NAME’].
Using $_SERVER[‘SCRIPT_NAME’]: $_SERVER is an array of stored information such as headers, paths, and script locations. These entries are created by the webserver. There is no other way that every web server will provide any of this information.
Syntax: ‘SCRIPT_NAME’ gives the path from the root to include the name of the directory.
- To get the current file name. We use
$currentPage= $_SERVER['SCRIPT_NAME'];
PHP code: The following is the complete code to get the current file name with the directory name.
is_page() │ WP 1.5.0
Проверяет отображается ли страница «постоянной страницы». Можно указать ID, ярлык или заголовок страницы для проверки. Условный тег.
Вернет true при передаче пустых значений
Будьте внимательны, потому что следующие вызовы этой функции вернут true:
is_page( '' ) is_page( 0 ) is_page( '0' ) is_page( null ) is_page( false ) is_page( array() )
Нельзя использовать внутри Цикла WordPress
Из-за того что в при работе цикла переписываются некоторые глобальные переменные, is_page() не получится использовать внутри цикла. Впрочем, в этом нет необходимости. Чтобы использовать этот Тег шаблона после цикла, произвольный цикл (запрос на получение записей) надо сбросить функцией: wp_reset_query()
Возвращает
true|false . true, если отображается тип страницы: постоянной страницы и false, если отображается любой другой тип страницы.
Использование
ID, ярлык, заголовок страницы, которую нужно проверить. Можно указать массив из любых этих значений, чтобы выставить на проверку несколько разных страниц.
Также для вложенных страниц можно указать полный путь: parent-page/child-page/ . Тогда функция попробует получить страницу через get_page_by_path() и сравнит является ли указанный $page текущей страницей.
Примеры
#1 Заметка про кириллицу и ярлык (слаг)
Если у вас на сайте кириллица не меняется на латиницу — нет плагина Cyr-To-Lat или ему подобного, то при создании записи её ярлык изменяется и кириллица превращается в спец символы (контакты — %d0%ba%d0%be%d0%bd%d1%82%d0%b0%d0%ba%d1%82%d1%8b), поэтому при проверке нужно это учитывать. Т.е. если проверяется не заголовок, а ярлык (post_name), то делайте так:
is_page('о-сайте'); // неправильно is_page( sanitize_title('о-сайте') ); // правильно
#2 Функция в действии
Различные примеры использования — случаи когда функция возвращает true (срабатывает):
// Когда отображается любая постоянная страница. is_page(); // когда отображается страница с ID 42. is_page(42); // Когда отображается страница с заголовком "О сайте". is_page('О сайте'); // Когда отображается страница со слагом "o-saite". is_page('o-saite'); // Параметры можно комбинировать. is_page( [ 42, 'o-saite', 'О сайте' ] ); // Можно проверять несколько страниц одновременно. is_page( [ 'sample-page', 'contacts', 'parent-slug/page-name', '/parent-slug/page-name/', 23, 34 ] );
#3 Проверка находимся ли мы на дочерней странице у постоянной страницы
В WordPress нет функции is_subpage() . Но такую проверку можно сделать таким кодом:
global $post; // Если за пределами цикла if ( is_page() && $post->post_parent ) < // Это дочерняя страница >else < // Это не дочерняя страница >
Можно создать свою функцию is_subpage() . Добавьте такой код в файл темы functions.php. Она работает как же как первый пример: проверят является ли текущая страница дочерней, т.е. страница ли это вообще и есть ли у нее родительская страница.
Такую функцию полезно создавать, когда на сайте предполагается делать проверки как в примере 1 много раз.
/* * Проверят является ли текущая постоянная страница дочерней страницей * Возвращает true или false */ function is_subpage() < global $post; if ( is_page() && $post->post_parent ) < return $post->post_parent; > return false; >
Чтобы определить страницу «О сайте» или её дочернюю страницу, используйте этот пример. Этот пример может пригодится, когда нужно указать переменную для всей ветки страниц. Здесь мы укажем картинку для ветки:
if ( is_page( 'about' ) || '2' == $post->post_parent ) < // Это страница "О сайте" или её дочерняя страница $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'; // если мы на неопределенной странице, выведем картинку по умолчанию >
Создадим функцию, которая проверит все уровни вложенности, всю ветку подстраниц и если мы на одной из страниц ветки, то функция вернет true, в противном случае false. Т.е. предположим у нас есть страница «О нас» у нее есть дочерняя страница «Наши услуги», а у этой страницы есть еще дочерние страницы «Покраска» и «Отделка». В эту функцию передадим ID страницы «О нас» и она будет возвращать true если мы находимся на любой из указанных страниц:
/* * Проверка дочерних страниц по всем уровням вложенности * $pid = ID страницы все уровни дочерних страниц которой нужно проверить */ function is_tree( $pid )< global $post; // если мы уже на указанной странице выходим if ( is_page( $pid ) ) return true; $anc = get_post_ancestors( $post->ID ); foreach ( $anc as $ancestor ) < if( is_page() && $ancestor == $pid ) < return true; >> return false; >
#4 Проверка разделения страницы
В записях можно использовать шоткод . Такой код будет делить текст записи на несколько страниц. Это полезно, когда вам нужно вывести метаданные только на первой странице, разделенной на несколько страниц записи.
$paged = $wp_query->get( 'paged' ); if ( ! $paged || $paged < 2 )< // Пост не разделен на страницы или это не первая страница. >else < // Это 2,3,4 . страница разделенного поста. >
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : false; if ( $paged === false ) < // Пост не разделен на страницы или это не первая страница. >else < // Это 2,3,4 . страница разделенного поста. >
if ( 0 === get_query_var( 'page' ) ) < // Пост не разделен на страницы или это не первая страница. >else < // Это 2,3,4 . страница разделенного поста. >
Заметки
Список изменений
Код is_page() is page WP 6.2.2
function is_page( $page = '' ) < global $wp_query; if ( ! isset( $wp_query ) ) < _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' ); return false; >return $wp_query->is_page( $page ); >
Cвязанные функции
Условные теги (типов страниц и запросов)
- is_404()
- is_admin()
- is_archive()
- is_attachment()
- is_author()
- is_blog_admin()
- is_category()
- is_comment_feed()
- is_customize_preview()
- is_date()
- is_day()
- is_embed()
- is_feed()
- is_front_page()
- is_home()
- is_month()
- is_network_admin()
- is_page_template()
- is_paged()
- is_post_type_archive()
- is_preview()
- is_robots()
- is_search()
- is_single()
- is_singular()
- is_ssl()
- is_tag()
- is_tax()
- is_time()
- is_trackback()
- is_user_admin()
- is_year()
- wp_doing_ajax()
- wp_doing_cron()
Условные теги (все)
- cat_is_ancestor_of()
- category_exists()
- comments_open()
- email_exists()
- has_block()
- has_category()
- has_custom_header()
- has_excerpt()
- has_nav_menu()
- has_post_thumbnail()
- has_shortcode()
- has_tag()
- has_term()
- have_comments()
- have_posts()
- in_category()
- in_the_loop()
- is_active_sidebar()
- is_admin_bar_showing()
- is_child_theme()
- is_dynamic_sidebar()
- is_email()
- is_header_video_active()
- is_local_attachment()
- is_login()
- is_main_query()
- is_multi_author()
- is_multisite()
- is_nav_menu()
- is_new_day()
- is_plugin_active()
- is_post_type_hierarchical()
- is_sticky()
- is_taxonomy_hierarchical()
- is_textdomain_loaded()
- is_user_logged_in()
- pings_open()
- post_exists()
- post_password_required()
- shortcode_exists()
- tag_exists()
- taxonomy_exists()
- term_exists()
- term_is_ancestor_of()
- wp_attachment_is()
- wp_is_mobile()
- wp_is_post_autosave()
- wp_is_post_revision()
- wp_is_using_https()
- wp_script_is()