В этом файле нам нужно будет удалить все лишнее, оставив только структурные элементы, а также вызовы базовых WordPress-функций:
Комментарий-заполнитель в самой середине кода – то, куда мы затем вставим наши произвольные элементы.
Добавляем произвольное приветствие
Об этом уже позаботился сам WordPress. Нам достаточно вставить следующую строку:
Добавляем новые области виджетов
Давайте настроим новые области виджетов в WordPress, используя стандартный процесс. Мы сделаем это с помощью дополнительного файла функций, чтобы сохранить вещи реюзабельными от темы к теме. Мы создадим новый файл, archives-page-functions.php, поместив его в основной каталог темы, а также зарегистрируем две новые области виджетов:
If(!function_exists("archives_page_widgets_init")) : function archives_page_widgets_init() { /* First archive page widget, displayed to the LEFT. */ register_sidebar(array("name" => __("Archives page widget LEFT", "zerif-lite"), "description" => __("This widget will be shown on the left side of your archive page.", "zerif-lite"), "id" => "archives-left", "before_widget" => "
", "before_title" => "", "after_title" => "
",)); /* Second archive page widget, displayed to the RIGHT. */ register_sidebar(array("name" => __("Archives page widget RIGHT", "zerif-lite"), "description" => __("This widget will be shown on the right side of your archive page.", "zerif-lite"), "id" => "archives-right", "before_widget" => " ", "before_title" => "", "after_title" => "
",)); } endif; add_action("widgets_init", "archives_page_widgets_init");If(!function_exists("archives_page_styles")) : function archives_page_styles() { if(is_page_template("tmpl_archives.php")) { wp_enqueue_style("archives-page-style", get_template_directory_uri() . "/archives-page-style.css"); // standard way of adding style sheets in WP. } } endif; add_action("wp_enqueue_scripts", "archives_page_styles");
Это условная операция постановки в очередь. Она будет работать только в том случае, если посетитель просматривает архивную страницу.
Нужно не забыть включить наш новый файл archives-page-functions.php путем добавления следующей строки в самый конец файла functions.php текущей темы:
Require get_template_directory() . "/archives-page-functions.php";
Наконец, новый блок, который мы будем использовать в нашем основном файле content-tmpl_archives.php, достаточно простой. Поместите следующий код под вызовом the_content();:
Все, что нам теперь останется – это позаботиться о единственно недостающем файле, archives-page-style.css. Однако давайте оставим его на потом, поскольку мы будем использовать его в качестве хранилища всех стилей нашей произвольной архивной страницы, в том числе и для виджетов.
Вывод последних 15 записей
Для этого нам нужно провести некоторое ручное кодирование PHP. Даже учитывая то, что вывод записей можно реализовать с помощью разнообразных виджетов, давайте избежим однообразия и погрузимся в написание кода, чтобы продемонстрировать больше разных возможностей.
Вы, вероятно, спросите, почему именно 15 записей? Не знаю, просто взял это число с потолка. Давайте сделаем его настраиваемым с помощью произвольных полей.
Вот, что мы сделаем:
- Задаем количество записей через произвольное поле archived-posts-no.
- Если число не является корректным, шаблон будет использоваться стандартное значение в 15 последних записей.
Ниже представлен код, который делает это. Поместите его под предыдущей секцией в файле content-tmpl_archives.php, который обрабатывает новые области виджетов.
ID, "archived-posts-no", true)); /* Here, we"re making sure that the number fetched is reasonable. In case it"s higher than 200 or lower than 2, we"re just resetting it to the default value of 15. */ if($how_many_last_posts > 200 || $how_many_last_posts < 2) $how_many_last_posts = 15; $my_query = new WP_Query("post_type=post&nopaging=1"); if($my_query->have_posts()) { echo "
"; echo "
- ";
$counter = 1;
while($my_query->have_posts() && $counter <= $how_many_last_posts) {
$my_query->the_post();
?>
- ">
Все, что делает этот код – это получает значение произвольного поля, задает количество выводимых записей, после чего выбирает эти записи из базы данных, используя WP_Query();. Также я использую некоторые иконки Font Awesome, чтобы добавить данному блоку некоторый шарм.
Вывод ссылок на авторские архивы
Этот раздел полезен только в том случае, если вы работаете с блогом с многочисленными авторами. Пропустите его, если у вас один автор.
Эта функциональность может быть реализована при помощи простого блока кода, который нужно поместить в наш файл content-tmpl_archives.php (под предыдущим блоком):
Our Authors
Мы перейдем к стилям через пару минут. В данный момент обратите внимание на что, что все делается с помощью вызова функции wp_list_authors().
Вывод ссылок на архивы по месяцам
Я добавил этот элемент в самый конец, поскольку это не самый полезный компонент с точки зрения читателей. Однако его важно иметь на архивной странице, чтобы вам не пришлось использовать виджеты для вывода архивов по месяцам в других местах сайта.
Вот, как это будет выглядеть в файле content-tmpl_archives.php:
By Month
В данном случае мы выведем это в виде отдельного абзаца с записями, разделенными прямым слэшем (|).
Полный шаблон архивной страницы
Давайте взглянем на полный файл content-tmpl_archives.php, который является нашим основным файлом для вывода произвольного архива:
Last ".$how_many_last_posts." Posts
";
echo "";
$counter = 1;
while($my_query->have_posts() && $counter <= $how_many_last_posts) {
$my_query->the_post();
?>
Our Authors
By Month
Таблица стилей
Наконец, давайте посмотрим на таблицу стилей. Вот как выглядит файл archives-page-style.css:
Archives-widget-left { float: left; width: 50%; } .archives-widget-right { float: left; padding-left: 4%; width: 46%; } .archives-latest-section { } .archives-latest-section ol { font-style: italic; font-size: 20px; padding: 10px 0; } .archives-latest-section ol li { padding-left: 8px; } .archives-authors-section { } .archives-authors-section ul { list-style: none; text-align: center; border-top: 1px dotted #888; border-bottom: 1px dotted #888; padding: 10px 0; font-size: 20px; margin: 0 0 20px 0; } .archives-authors-section ul li { display: inline; padding: 0 10px; } .archives-authors-section ul li a { text-decoration:none; } .archives-by-month-section { ext-align: center; word-spacing: 5px; } .archives-by-month-section p { border-top: 1px dotted #888; border-bottom: 1px dotted #888; padding: 15px 0; } .archives-by-month-section p a { text-decoration:none; } @media only screen and (max-width: 600px) { .archives-widget-left { width: 100%; } .archives-widget-right { width: 100%; } }
В основном стили касаются шрифтов и нескольких структурных элементов, за исключением пары выравниваний, а также блока адаптивного дизайна в конце.
Давайте посмотрим, как это будет выглядеть на практике. Вот сайт, который имеет массу контента в архиве:
Как интегрировать этот шаблон в любую тему
Произвольная страница архивов, которую мы создали здесь, представлена для темы Zerif Lite, которая имеется в официальном каталоге WordPress. Однако, как я уже говорил, она может использоваться вместе с любой темой. Вот как это сделать:
- Берем файлы archives-page-style.css и archives-page-functions.php, которые мы создали в руководстве, после чего помещаем их в главный каталог темы.
- Редактируем functions.php темы и добавляем следующую строку в самый конец: require get_template_directory() . ‘/archives-page-functions.php’;
- Берем файл page.php темы, делаем его копию, переименовываем ее, меняем вызов функции get_template_part() на get_template_part(‘content’, ‘tmpl_archives’);, после чего добавляем описательный комментарий в самое начало: /* Template Name: Archive Page Custom */.
- Берем файл content-page.php вашей темы, делаем его копию, переименовываем его в content-tmpl_archives.php, и добавляем в него все произвольные блоки, которые мы создали в руководстве, сразу под вызовом функции the_content();.
- Тестируем и наслаждаемся.
Вот как это будет выглядеть в стандартной теме Twenty Fifteen:
Here are the most important news items we have published in 2008 on сайт.
Update (December 6th): Added missing zip security fix
There have been a great number of other additions and improvements since the last alpha, but here is a short overview of the most important changes:
- (documentation has been updated to the current state)
- ext/msql has been removed, while ext/ereg will now raise E_DEPRECATED notices
- ext/mhash has been replaced by ext/hash but full BC is maintained
- PHP now uses cc as the default compiler, instead of gcc
- A number of bug fixes to ext/pdo, ext/soap, the stream layer among others
Several under the hood changes also require in depth testing with existing applications to ensure that any backwards compatibility breaks are minimized.
We would love developers, designers, managers or anyone else with an interest in the PHP programming language to join us for what promises to be an awesome event at a very reasonable rate:
- Standard tickets: £60.00
- Early bird (until 8th November): £50.00
- Concessionary tickets: £35.00
* Confirmation with your company"s letter head
** With Student ID. Limited seating available
The purpose of this alpha release is to encourage users to not only actively participate in identifying bugs, but also in ensuring that all new features or necessary backwards compatibility breaks are noted in the documentation. Please report any findings to the or the .
There have been a great number of other additions and improvements, but here is a short overview of the most important changes:
- (documentation maybe out dated)
- Addition of the , (phar is scheduled for some more work a head of alpha2), and extensions
- Optional cyclic garbage collection
- Optional support for the MySQLnd replacement driver for libmysql
- Windows older than Windows 2000 (Windows 98, NT4, etc.) are not supported anymore ()
- New syntax features like , limited GOTO, ternary short cut "?:"
Several under the hood changes also require in depth testing with existing applications to ensure that any backwards compatibility breaks are minimized. This is especially important for users that require the undocumented Zend engine multibyte support.
Our top submitter Felix De Vliegher has actually committed his last submissions himself since, based on the high quality of his submissions, he has been granted commit rights to the PHP repository. We have not heard back from all participants, but we encourage everybody to blog about their experience and provide us with feedback on how to improve future events.
Now better late than never, here are the 10 winners of the promised elePHPant raffle sponsored by Nexen . Note that Felix asked me not to include him in the raffle, since he is already herding quite a number of elePHPants at home.
- Eric Stewart
- Håvard Eide
- Marc Veldman
- Michelangelo van Dam
- Rein Velt
- Rob Young
- Sami Greenbury
- Sebastian Deutsch
- Sebastian Schürmann
- Stefan Koopmanschap
We will provide Nexen with the email addresses of the winners, so that they can arrange to get the elePHPants shipped. Also for those people wondering, you can continue to submit tests on the . A bit thank you to all participants and TestFest organizers! Without the countless people that helped organize local events, implement the infrastructure and submissions reviewers, the TestFest would have obviously not worked out as well as it has. We will surely do similar events in the future based on the big success of TestFest 2008.
Security Enhancements and Fixes in PHP 5.2.6:
- Fixed possible stack buffer overflow in the FastCGI SAPI identified by Andrei Nigmatulin.
- Fixed integer overflow in printf() identified by Maksymilian Aciemowicz.
- Fixed security issue detailed in CVE-2008-0599 identified by Ryan Permeh.
- Fixed a safe_mode bypass in cURL identified by Maksymilian Arciemowicz.
- Properly address incomplete multibyte chars inside escapeshellcmd() identified by Stefan Esser.
- Upgraded bundled PCRE to version 7.6
Читайте также...
- Создаем произвольную страницу архивов в WordPress Как интегрировать этот шаблон в любую тему
- Удалённое включение компьютера бесплатно, без SMS и без облаков, с помощью Mikrotik
- Профессии: администратор группы в соц
- Как удалить программу с "андроида", в том числе стандартную Приложение настольные разных фруктов андроид как удалить