в части страницы.

wp_title() │ WP 1.0.0

Функция считается устаревшей с версии 4.4. Вместо неё следует использовать поддержку темы ‘title-tag’:

/* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' );

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

Хуки из функции

Возвращает

Использование

$sep(строка) Текст, который будет показан до или после заголовка (разделитель). По умолчанию сепаратором будет символ: » .
По умолчанию: » (») $echo(логический) Выводить (true) или возвращать заголовок в переменную (false). По умолчанию заголовок выводится на экран.
По умолчанию: true $seplocation(строка) Определяет расположение разделителя. Введено в версии 2.5. Если указать right , то разделитель будет расположен справа от заголовка, во всех остальных случаях слева.
По умолчанию: »

Примеры

#1 Выведем заголовок блога

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

Читайте также:  Python ctypes string at

#2 Если нужно убрать разделитель, то вызываем функцию так:

#3 Поменяем местами заголовки

#4 Отдельный заголовок для главной страницы

Если для главной страницы мы используем произвольный шаблон, с произвольный выводом (Циклом WordPress), то заголовок страницы может определяться не так как нам бы хотелось. Чтобы избежать этого используйте такой код:

#5 Использование разделителей

Заметки

Список изменений

Код wp_title() wp title WP 6.2.2

function wp_title( $sep = '»', $display = true, $seplocation = '' ) < global $wp_locale; $m = get_query_var( 'm' ); $year = get_query_var( 'year' ); $monthnum = get_query_var( 'monthnum' ); $day = get_query_var( 'day' ); $search = get_query_var( 's' ); $title = ''; $t_sep = '%WP_TITLE_SEP%'; // Temporary separator, for accurate flipping, if necessary. // If there is a post. if ( is_single() || ( is_home() && ! is_front_page() ) || ( is_page() && ! is_front_page() ) ) < $title = single_post_title( '', false ); >// If there's a post type archive. if ( is_post_type_archive() ) < $post_type = get_query_var( 'post_type' ); if ( is_array( $post_type ) ) < $post_type = reset( $post_type ); >$post_type_object = get_post_type_object( $post_type ); if ( ! $post_type_object->has_archive ) < $title = post_type_archive_title( '', false ); >> // If there's a category or tag. if ( is_category() || is_tag() ) < $title = single_term_title( '', false ); >// If there's a taxonomy. if ( is_tax() ) < $term = get_queried_object(); if ( $term ) < $tax = get_taxonomy( $term->taxonomy ); $title = single_term_title( $tax->labels->name . $t_sep, false ); > > // If there's an author. if ( is_author() && ! is_post_type_archive() ) < $author = get_queried_object(); if ( $author ) < $title = $author->display_name; > > // Post type archives with has_archive should override terms. if ( is_post_type_archive() && $post_type_object->has_archive ) < $title = post_type_archive_title( '', false ); >// If there's a month. if ( is_archive() && ! empty( $m ) ) < $my_year = substr( $m, 0, 4 ); $my_month = substr( $m, 4, 2 ); $my_day = (int) substr( $m, 6, 2 ); $title = $my_year . ( $my_month ? $t_sep . $wp_locale->get_month( $my_month ) : '' ) . ( $my_day ? $t_sep . $my_day : '' ); > // If there's a year. if ( is_archive() && ! empty( $year ) ) < $title = $year; if ( ! empty( $monthnum ) ) < $title .= $t_sep . $wp_locale->get_month( $monthnum ); > if ( ! empty( $day ) ) < $title .= $t_sep . zeroise( $day, 2 ); >> // If it's a search. if ( is_search() ) < /* translators: 1: Separator, 2: Search query. */ $title = sprintf( __( 'Search Results %1$s %2$s' ), $t_sep, strip_tags( $search ) ); >// If it's a 404 page. if ( is_404() ) < $title = __( 'Page not found' ); >$prefix = ''; if ( ! empty( $title ) ) < $prefix = " $sep "; >/** * Filters the parts of the page title. * * @since 4.0.0 * * @param string[] $title_array Array of parts of the page title. */ $title_array = apply_filters( 'wp_title_parts', explode( $t_sep, $title ) ); // Determines position of the separator and direction of the breadcrumb. if ( 'right' === $seplocation ) < // Separator on right, so reverse the order. $title_array = array_reverse( $title_array ); $title = implode( " $sep ", $title_array ) . $prefix; >else < $title = $prefix . implode( " $sep ", $title_array ); >/** * Filters the text of the page title. * * @since 2.0.0 * * @param string $title Page title. * @param string $sep Title separator. * @param string $seplocation Location of the separator ('left' or 'right'). */ $title = apply_filters( 'wp_title', $title, $sep, $seplocation ); // Send it out. if ( $display ) < echo $title; >else < return $title; >>

Cвязанные функции

Другие функции темы

  • add_theme_support()
  • bloginfo()
  • body_class()
  • current_theme_supports()
  • get_custom_header_markup()
  • get_custom_logo()
  • get_header_image()
  • get_header_image_tag()
  • get_header_textcolor()
  • get_header_video_url()
  • get_page_template()
  • get_page_templates()
  • get_post_class()
  • get_query_template()
  • get_stylesheet()
  • get_template()
  • get_theme_mod()
  • get_theme_mods()
  • get_theme_root()
  • has_custom_logo()
  • has_header_image()
  • has_header_video()
  • header_image()
  • is_child_theme()
  • is_header_video_active()
  • post_class()
  • register_nav_menu()
  • register_nav_menus()
  • register_theme_directory()
  • remove_theme_mod()
  • remove_theme_mods()
  • remove_theme_support()
  • search_theme_directories()
  • set_theme_mod()
  • single_month_title()
  • the_custom_header_markup()
  • the_custom_logo()
  • the_header_video_url()
  • the_search_query()
  • unregister_nav_menu()
  • wp_body_open()
  • wp_custom_css_cb()
  • wp_footer()
  • wp_get_archives()
  • wp_get_document_title()
  • wp_get_theme()
  • wp_get_themes()
  • wp_head()
  • wp_is_mobile()
  • wp_nav_menu()
  • wp_robots()
  • wp_site_icon()
Читайте также:  Font css шрифты подключить

Основные

  • calendar_week_mod()
  • get_archives_link()
  • get_bloginfo()
  • get_calendar()
  • get_current_blog_id()
  • get_footer()
  • get_header()
  • get_search_form()
  • get_sidebar()
  • get_template_part()
  • is_404()
  • is_active_sidebar()
  • is_admin()
  • is_archive()
  • is_attachment()
  • is_author()
  • is_category()
  • is_comment_feed()
  • is_date()
  • is_day()
  • is_dynamic_sidebar()
  • is_embed()
  • is_feed()
  • is_front_page()
  • is_home()
  • is_month()
  • is_page_template()
  • is_paged()
  • is_post_type_archive()
  • is_preview()
  • is_search()
  • is_single()
  • is_singular()
  • is_ssl()
  • is_sticky()
  • is_tag()
  • is_tax()
  • is_year()
  • language_attributes()
  • post_type_archive_title()
  • register_sidebar()
  • setup_postdata()
  • the_archive_description()
  • the_archive_title()
  • wp_enqueue_script()
  • wp_enqueue_style()
  • wp_login_form()
  • wp_login_url()
  • wp_loginout()
  • wp_logout_url()
  • wp_lostpassword_url()
  • wp_register()

Источник

Php title in array

Итак, по порядку. К примеру я создаю файл generation_title.php
В него пихаю этот код :
===============================================

$titles = array(
‘id index.php’ => ‘заголовок страницы индекса’,
);

if (in_array($_GET[‘page’], $titles))
$title = $titles[$_GET[‘page’];
>

?>
===============================================
потом естественно вставляю полученный файл в генерацию самой странички (к примеру для index.php):

Всё это сделал, вот что пишет браузер :

Parse error: syntax error, unexpected ‘;’, expecting ‘]’ in /home/site/public_html/generation_title.php on line 17

только вернулся с phpconf 2008, и тут на тебе

во-первых, у тебя же написано, что за ошибка и где она находится (пропущена закрывающая квадратная скобка в препоследней строке кода). чтобы легко находить синтаксические ошибки и быстро писать php-код, скачай себе zend studio.

во-вторых, эта самая строчка кода в принципе не имеет смысла
ведь функция in_array проверяет наличие в значениях массива, а переменная $_GET[‘page’] должна присутствовать в его ключах. id страниц являются в этом массиве именно ключами. поэтому здесь надо использовать функцию array_key_exists

в-третьих, что у тебя id-то такие идиотские?

в-четвертых, где блок else для if’а?

Раз 20 прочитал твой ответ — я ни бум-бум.;)
Слушай, раз ты посещаешь такие мероприятия как phpconf 2008 — значит ты монстр в этом деле.
Чесно я в php — мало чего понимаю. Пользоваться готовыми шаблонами это одно, а вот что б вот так вот взять и самому написать код, это мне не под силу. Последнее на чём я програмировал это был Бейсик, да и то во времена ZX Specturm.
Мож поможешь с кодом ? Как он правильно должен быть написан в моём случае ?

P.S. zend studio — там кокой релиз то качать ?

короче
поменяй код на это:

$titles = array(
‘page1’ => ‘заголовок страницы один’
);

if (array_key_exists($_GET[‘page’], $titles));
$title = $titles[$_GET[‘page’]];
>
else
$title = ‘заголовок страницы индекса’;
>

и попробуй зайти на http://твойсайт/?page=page1

zend studio надо качать версии 5.5

Иридий ! Я всётаки асилил динамический title. Делал по одному примеру из инета.

Суть :
к примеру в файл index.php (так придётся поступить со всему php’шками) инклудим файл dinamic_tittle.php

далее пихаем код в собственно сам dinamic_tittle.php

if($_SERVER[‘REQUEST_URI’]==»/index.php») echo «Ля-ля-ля-ля 1 «;
elseif($_SERVER[‘REQUEST_URI’]==»/и так далее.php») echo «Ля-ля-ля-ля 2 «;

else echo «Для всех остальных страниц «;

После обработки браузером титл выглядит так : «Ля-ля-ля-ля Название компании»

Всё работает ! Я сам в ахуе.

Вопрос № 1 : как поступить по аналогии с keywords и description ?
Вопрос № 2 : а стоит ли это делать ? Помоему поисковикам пох на эти теги.
Вопрос № 3 : чем больше вот таких вот генираций, тем дольше будет грузицца страница ? Нежели это всё прописать явным образом ?

Цитата от: m.d.3d на 11 июля 2008, 08:57:13
Иридий ! Я всётаки асилил динамический title. Делал по одному примеру из инета.

Суть :
к примеру в файл index.php (так придётся поступить со всему php’шками) инклудим файл dinamic_tittle.php

далее пихаем код в собственно сам dinamic_tittle.php

if($_SERVER[‘REQUEST_URI’]==»/index.php») echo «Ля-ля-ля-ля 1 «;
elseif($_SERVER[‘REQUEST_URI’]==»/и так далее.php») echo «Ля-ля-ля-ля 2 «;

else echo «Для всех остальных страниц «;

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

switch ($_SERVER[‘REQUEST_URI’])
case ‘/index.php’:
$title = ‘Ля-ля-ля-ля 1’;
$description = ‘тополя1’;
$keywords = ‘тратата1’;
break;

case ‘/и так далее.php’:
$title = ‘Ля-ля-ля-ля 1’;
$description = ‘тополя1’;
$keywords = ‘тратата1’;
break;

Источник

How to echo the_title from an array of posts?

When I run this script it shows a post which is not in cat 3. but if I do print_r($post) it shows the correct three posts. Any idea of where I’m getting wrong?

2 Answers 2

global $post; $args = array('posts_per_page' =>3,'category' => 3 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); the_title() endforeach; wp_reset_postdata(); 

I’m trying to put the posts into an array as you can see in my code I’ve used $posts = array() and $posts[] and that’s because I’d run multiple queries and get posts out of them

query_posts() clobbers the global variable $wp_query . Don’t use it:

Note: This function isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.

http://codex.wordpress.org/Function_Reference/query_posts

Note the very first line: «This function isn’t meant to be used by plugins or themes.«

Someone has already mentioned get_posts() , which is perfectly valid. However, I tend to prefer WP_Query for just about everything related to post retrieval, so I’d lean toward something like:

$args = array( 'posts_per_page' => 3, 'cat' => 1 ); $cp = new WP_Query( $args ); foreach ($cp->posts as $p) < echo apply_filters('the_title',$p->post_title); > 

Источник

Оцените статью