Ленивый add review php. Как создавать произвольные типы записей WordPress
Шаблоны файлов WooCommerce содержат разметку и структуру шаблона интерфейса (и HTML сообщения электронной почты) вашего магазина. Если Вы откроете эти файлы, то Вы заметите, что все они содержат много хуков (hooks), которые позволят Вам добавлять / перемещать контент без необходимости редактирования самих файлов шаблона. Такой подход защищает от любых проблем с обновлениями, так как файлы шаблона могут оставаться полностью нетронутыми.
Кроме того, вы можете редактировать эти файлы безопасным способом с помощью подмены. Просто скопируйте их в Ваш шаблон в папку с именем /woocommerce , сохраняя ту же иерархическую структуру вложенных файлов и папок. Скопированные файлы шаблонов переопределят файлы шаблонов WooCommerce, используемые по умолчанию. Не редактируйте файлы шаблонов в ядре самого плагина, так как они будут перезаписаны в процессе обновления и все внесенные в них изменения будут потеряны, поскольку обновленные файлы шаблонов затрут старые файлы шаблонов.
Если Вы хотите внести изменения в один из шаблонов , то нет необходимости копировать все файл шаблонов, расположенные в папке templates, а достаточно скопировать только файл шаблона, в который Вы хотите внести изменения . Для этого с директории в вашей темой создайте папку woocommerce и перенесите в нее шаблон, соблюдая вложенность папок.
Пример: для внесения изменений в шаблон корзины, скопируйте woocommerce/templates/cart/cart.php в . После этого Вы можете вносить любые изменения в файл шаблона cart.php , расположенный в папке с вашей темой (т.е. в файл cart.php, расположенный по адресу ваша_тема/woocommerce/cart/cart.php ), и внесенные вами изменения сохранятся даже после обновления WooCommerce.
В директории /woocommerce/templates/ можно найти следующие файлы шаблонов
Спойлер: Список файлов
(данный список файлов шаблонов актуален для версии WooCommerce 2.0+):
· archive-product.php
· cart/
· cart-empty.php
· cross-sells.php
· mini-cart.php
· shipping-calculator.php
· shipping-methods.php
· totals.php
· checkout/
· cart-errors.php
· form-billing.php
· form-checkout.php
· form-coupon.php
· form-login.php
· form-pay.php
· form-shipping.php
· review-order.php
· thankyou.php
· content-product_cat.php
· content-product.php
· content-single-product.php
· emails/
· admin-new-order.php
· customer-completed-order.php
· customer-invoice.php
· customer-new_account.php
· customer-note.php
· customer-processing-order.php
· customer-reset-password.php
· email-addresses.php
· email-footer.php
· email-header.php
· email-order-items.php
· loop/
· add-to-cart.php
· loop-end.php
· loop-start.php
· no-products-found.php
· pagination.php
· result-count.php
· sale-flash.php
· myaccount/
· form-change-password.php
· form-edit-address.php
· form-login.php
· form-lost-password.php
· my-account.php
· my-address.php
· my-downloads.php
· my-orders.php
· order/
· form-tracking.php
· order-details.php
· tracking.php
· shop/
· breadcrumb.php
· form-login.php
· messages.php
· wrapper-end.php
Мы также включим функцию редактора записей Custom Fields (пользовательские или произвольные поля) для каждого типа и отобразим поля в новых шаблонах.
В WordPress пользовательские типы записей дают вам полный контроль над тем, как отображать контент вашим пользователям. Если вы создаёте записи в своём блоге, вы можете создать индивидуальные стили только для них. Если вы пишете отзывы о музыке или фильмах, вы можете добавлять дополнительные области для ввода в нужных публикациях, и они не будут отображаться в других публикациях блога.
Но прежде чем мы продолжим, давайте разберёмся с тем, что такое пользовательские записи.
Что такое произвольные типы записей WordPress?
Если коротко, то произвольные типы записей WordPress позволяют вам сортировать публикации по их содержимому. В WordPress типы публикаций по умолчанию: Запись, Страница, Медиафайлы и др.
Обычно вы пишете все ваши публикации в разделе Записи в админ консоли, затем присваиваете им категорию. Все записи различных типов находятся в одном списке, что затрудняет их различие по типу содержимого.
Произвольные типы записей со своими собственными ссылками в админ консоли ведут вас к списку записей этого типа. Созданным таким образом публикациям могут быть присвоены категории, такие как обычная запись, поэтому у вас есть абсолютная свобода сортировать и представлять публикации любым способом.
В примере выше, если пользователь перейдёт в раздел базы данных фильмов (movie) на вашем сайте, публикации с отзывами (review) не будут включены. Если вы, к примеру, сделаете категории ‘Action’ и ‘Romance’, ваши пользователи смогут пойти в категорию фильмов Action и увидеть все отзывы и фильмы категории.
Когда создаёте новый тип публикации, у вас есть множество настроек, таких как: где в админ-меню будет расположена ссылка, будет ли этот тип включён в результаты поиска, будет ли поддерживаться отображение фрагмента текста, разрешены ли комментарии и так далее.
Вы можете изменить различные тексты названий (заданные с использованием массива $labels ), такие как переименовать Add New Post в Add New Movie . Например, вы можете переименовать текст Featured Image (Изображение записи) в Add Poster (Добавить постер) .
Вы также можете включить функцию пользовательских полей в своём редакторе публикаций, которая по умолчанию спрятана и должна быть включена при помощи ссылки Screen Options вверху редактора.
Продолжая пример с Movies и Movie Reviews, публикации Movie могут добавлять пользовательские/произвольные поля для таких параметров как год выпуска, режисёр, рейтинги многие другие с кратким обзором фильмы в виде содержимого записи.
Обычно любое поле, которое вы создадите, доступно в любом типе записей, поэтому плагин требует ограничений для каждого поля, где ему быть доступным.
Создание новых типов записей
Когда вы создаёте значительные изменения в WordPress, одним из доступных вариантов реализации является создание плагина . Вы также можете создавать новые произвольные типы записей в файле functions.php . Для этого руководства мы создадим плагин и продолжим использовать пример с базой данных movie/reviews (фильмы/отзывы).
Для создания пользовательского типа записи нужно написать несколько функций, которые вызывают функцию WordPress с названием register_post_type() с двумя параметрами. Ваша функция должна быть привязана к хуку действия(action hook) init , иначе произвольный тип записи не будет зарегистрирован верно.
// The custom function MUST be hooked to the init action hook add_action("init", "lc_register_movie_post_type"); // A custom function that calls register_post_type function lc_register_movie_post_type() { // Set various pieces of text, $labels is used inside the $args array $labels = array("name" => _x("Movies", "post type general name"), "singular_name" => _x("Movie", "post type singular name"), ...); // Set various pieces of information about the post type $args = array("labels" => $labels, "description" => "My custom post type", "public" => true, ...); // Register the movie post type with all the information contained in the $arguments array register_post_type("movie", $args); }
Все пользовательские функции должны иметь префикс, чтобы избежать конфликтов с другими плагинами или функциями темы. Здесь будет использоваться префикс LC.
Два параметра для функции register_post_type() это:
- Название типа записи, максимум 20 символов, и не должно содержать пробелов и заглавных букв
- Ассоциативный массив, под названием $args , который содержит информацию о типе записи в виде пар ключ значение ‘key’ => ‘value’
Массив $args
Наиболее часто используемые ключи для массива $args показаны ниже, все не являются обязательными:
- labels – массив array , который задаёт разные фрагменты текста, например ‘Добавить новую запись’ может быть переименована в ‘Добавить новый фильм’. Ключи для массива labels с пояснениями описаны ниже;
- description – короткое и ёмкое описание типа записи, оно может быть отображено в шаблонах типов, но больше нигде не используется;
- public – видно ли тип записи для автором и посетителей, значение по умолчанию FALSE, что значит он не появляется даже в Админ консоли;
- exclude_from_search – будут ли записи этого типа появляться в результатах обычного поиска, значение по умолчанию противоположное значению public;
- publicly_queryable – можно ли получить запись этого типа с помощью URL-адреса, например, http://www.mywebsite.com/?post_type=movie, или в расширенном использовании через функцию query_posts(). Значение по умолчанию, это значение public;
- show_ui – подключаются ли ссылки меню и редактор сообщений в панели управления администратора. Значение по умолчанию –public;
- show_in_nav_menus – будут ли записи этого типа добавляться в меню навигации, созданные на странице Внешний вид ->Меню, значение по умолчанию – это значение public;
- show_in_menu – отображается ли ссылка типа записи в навигации админ консоли. FALSE – скрывает ссылку. TRUE – добавляет ссылку как новую ссылку верхнего уровня. Ввод строки позволяет разместить ссылку внутри существующей ссылки верхнего уровня, то есть ввести параметры options-general.php располагает её под ссылкой Настройки.
- show_in_admin_bar – появится ли этот тип записей выше Admin bar, под ссылкой + New
- menu_position – позиция новой ссылки в меню навигации админ консоли, 5 располагает ниже Записей, 100 располагает ниже Настроек, весь список позиций можно найти в WordPress Codex
- hierarchical – может ли запись быть назначена к родительской записи, если значение TRUE, то массив $supports должен содержать параметр ‘page-attributes’
- supports – выборочно включает функции записи такие как: изображения, фрагменты текста, произвольные поля и др. Если установлено в FALSE, то вместо массива выключается редактор для этого типа поста – полезно, если вы хотите закрыть все записи этого типа от редактирования, но оставить видимыми (список значений массива ниэе)
- taxonomies – массив таксономий, который может быть применён к публикациям этого типа, таксономии должны быть уже зарегистрированными – отсюда они не создаются!
- has_archive – будут ли у записей этого типа архивные страницы, URL имеет структуру постоянной ссылки и описательная часть URL – это параметр 1 функции register_post_types(), то есть http://www.mywebsite.com/movie_reviews/ покажет все записи movie_review.
- query_var – TRUE или FALSE определяет, может ли запись быть показанной, вписывая в виде запроса в URL тип записи и имя записи, то есть ‘http://www.mywebsite.com/?movie =the-matrix ‘. Если вы вводите строку текста, нужно располагать текст после символа?, таким образом ‘film’ будет выглядеть в результате как ‘?film =the-matrix ‘.
Массивы labels
Первый ключ в массиве $args называется labels (ярлыки) и должен быть массивом. Он задаёт различные фрагменты текста, относящиеся к типу записи. Так как здесь может быть много данных, лучше всего создать массив с названием $labels для их хранения. Приведенный выше код немного проясняет, что это значит.
Ниже представлены некоторые важные ключи для массива labels, все не являются обязательными:
- name – общее названия для типа сообщений, например, movies (фильмы)
- singular_name – название для одной записи этого типа, например, movie (фильм)
- add_new – замена текста ‘Add New’ (Добавить новую) на указанный текст, например, ‘Add Movie’ (Добавить фильм)
- add_new_item – замена для ‘Add New Post’ (Добавить новую запись), например, на ‘Add New Movie’ (Добавить новый фильм)
- edit_item – замена для ‘Edit Post’ (Редактировать запись), например, на ‘Edit Movie’ (Редактировать Фильм)
- featured_image – замена для ‘Featured Image’ (Изображение записи) в редакторе записи, например, на ‘Movie Poster’
- set_featured_image – замена ‘Set Featured Image’, к примеру, на такой вариант ‘Add Movie Poster’
- menu_name – изменение текста ссылки на верхнем уровне, текст для ссылки по умолчанию имя ключа
Массив supports
// Enable specific features in the post editor for my post type $supports = array ("title", "editor", "author", "thumbnail"); // Disable ALL features of the post editor for my post type $supports = FALSE;Один из ключей в массиве $args называется supports . Это простой массив, где вы записываете список функций редактора записи, которые вы хотите включить для своего типа записи. По умолчанию только название (title) и редактор (editor) включены.
Вы также можете поставить FALSE вместо массива, для отключение всех функций редактора, выключая и title, и область добавления контента. Это означает, что запись не может быть отредактирована, но по прежнему полностью видна.
Вот перечень функций, которые вы можете включить в массиве $supports :
- title (название)
- editor (редактор)
- author – ПРИМЕЧАНИЕ: это позволяет вам изменять автора публикации
- thumbnail (иконка)
- excerpt (фрагмент текста)
- trackbacks (трекбек)
- custom-fields (произвольное поле)
- comments (комментарии)
- revisions (версии)
- page-attributes (атрибуты страницы)
- post-formats (форматы записи)
Создание произвольного типа записи WordPress через плагин
Теперь, когда мы знаем, какие параметры нужны для функции, мы можем создать свой плагин, написать собственную функцию и прикрепить её к событию init .
lc_custom_post_movie() to the init action hook add_action("init", "lc_custom_post_movie"); // The custom function to register a movie post type function lc_custom_post_movie() { // Set the labels, this variable is used in the $args array $labels = array("name" => __("Movies"), "singular_name" => __("Movie"), "add_new" => __("Add New Movie"), "add_new_item" => __("Add New Movie"), "edit_item" => __("Edit Movie"), "new_item" => __("New Movie"), "all_items" => __("All Movies"), "view_item" => __("View Movie"), "search_items" => __("Search Movies"), "featured_image" => "Poster", "set_featured_image" => "Add Poster"); // The arguments for our post type, to be entered as parameter 2 of register_post_type() $args = array("labels" => $labels, "description" => "Holds our movies and movie specific data", "public" => true, "menu_position" => 5, "supports" => array("title", "editor", "thumbnail", "excerpt", "comments", "custom-fields"), "has_archive" => true, "show_in_admin_bar" => true, "show_in_nav_menus" => true, "has_archive" => true, "query_var" => "film"); // Call the actual WordPress function // Parameter 1 is a name for the post type // Parameter 2 is the $args array register_post_type("movie", $args); } // Hook lc_custom_post_movie_reviews() to the init action hook add_action("init", "lc_custom_post_movie_reviews"); // The custom function to register a movie review post type function lc_custom_post_movie_reviews() { // Set the labels, this variable is used in the $args array $labels = array("name" => __("Movie Reviews"), "singular_name" => __("Movie Review"), "add_new" => __("Add New Movie Review"), "add_new_item" => __("Add New Movie Review"), "edit_item" => __("Edit Movie Review"), "new_item" => __("New Movie Review"), "all_items" => __("All Movie Reviews"), "view_item" => __("View Movie Reviews"), "search_items" => __("Search Movie Reviews")); // The arguments for our post type, to be entered as parameter 2 of register_post_type() $args = array("labels" => $labels, "description" => "Holds our movie reviews", "public" => true, "menu_position" => 6, "supports" => array("title", "editor", "thumbnail", "excerpt", "comments", "custom-fields"), "has_archive" => true, "show_in_admin_bar" => true, "show_in_nav_menus" => true, "has_archive" => true); // Call the actual WordPress function // Parameter 1 is a name for the post type // $args array goes in parameter 2. register_post_type("review", $args); }
Ели вы включите этот плагин, то увидите новую ссылку в панели навигации админ консоли, сразу после ссылки Записи.
При наведении мыши будет показаны пункты меню ‘View All’ (Показать все) и ‘Add New’ (Добавить новую), текст будет соответствовать тому, который был задан в массиве $labels . Посмотрите в редакторе, где изменились ссылки.
Ограничение произвольных полей для заданных записей
При добавлении своих полей в запись поля сохраняются и вы можете быстро добавить любое к новой записи. Произвольные поля, которые вы добавили будут появляться в выпадающем списке каждой записи. Это может затруднить поиск нужного поля в определённых типах записей. Если вы хотите ограничить произвольные поля, чтобы они были доступны только для отдельных типов записей, то самый простой способ – через плагин.
get_post_meta()
- принимает 3 параметра и возвращает результат
- первый параметр – ID записи, вы можете использовать здесь $post->ID для получения ID текущей отображаемой записи
- второй параметр – имя произвольного поля записи, чувствительное к регистру
- третий параметр имеет тип boolean, называется $single и может быть TRUE (возвращает результат в виде строки) или FALSE (возвращает массив).
ID, "Box Art", TRUE); if (!empty($movie_box_art)) { ?>ПРИМЕЧАНИЕ: Вы можете создать несколько настраиваемых полей с тем же именем и разными значениями. Если существует несколько полей с одинаковым именем, установка FALSE вернёт их массив.
Поскольку функция get_post_meta() возвращает значение, вы можете использовать значение в условном выражении для соответствующего изменения внешнего вида.
В примере выше мы проверяем, содержит ли фильм (movie) box art, назначенный ему в виде произвольного поля. Если $movie_box_art не пустое, вывести div и image.
Отображение Advanced Custom Fields
// Display field value the_field("FIELD NAME"); // Return field value get_field("FIELD NAME");Плагин Advanced Custom Fields предлагает свои собственные функции и шорткоды для отображения полей.
the_field(‘ FIELD NAME’);
Отображает значение указанного поля, вы должны использовать имя поля (Field Name), которое вы указали при создании группы полей.
get_field(‘FIELD NAME’);
Возвращает значение указанного поля, удобно для условных выражений.
Это те функции, которые вам, скорее всего, понадобятся. Есть много дополнительных функций, и вы можете найти их в .
Шорткоды
Вы можете отображать поля непосредственно в записи, используя шорткод выше.
Отображение произвольного типа записей на главной странице
// Hook our custom function to the pre_get_posts action hook add_action("pre_get_posts", "add_reviews_to_frontpage"); // Alter the main query function add_reviews_to_frontpage($query) { if (is_home() && $query->is_main_query()) { $query->set("post_type", array("post", "movie", "review")); } return $query; }Пользовательские типы записей не отображаются на главной странице по умолчанию, поэтому вам нужно создать новую функцию, которая вызывает установленный метод объекта WP_Query WordPress.
Функция проверяет, находится ли посетитель на главной странице, и является ли активный запрос основным, созданным WordPress.
$query->set() принимает два параметра:
- первый параметр – приоритет, который вы хотите изменить, в нашем случае мы изменяем приоритет post_type
- второй параметр – массив, который вы хотите передать как значение признака post_type
В примере кода выше массив начинается с ‘post’ – вот почему каждая запись WordPress имеет тип ‘post’ и мы всё ещё хотим включить её на главной странице.
Если на главной странице вы хотите использовать только пользовательские записи заданного типа, вы можете удалить‘posts’ и использовать свой собственный тип сообщений.
Значение, которое вы вводите должно соответствовать параметру 1 функции register_post_type() .
Заключение
В этом руководстве, мы показываем как создать пользовательские типы и какие данные вам нужно иметь для этого. Гибкость произвольных типов публикаций предоставляет ценную функциональность для любого сайта на WordPress.
WordPress подразумевает кастомизацию/настройку. Он был создан таким образом, чтобы можно было настроить абсолютно каждый раздел. В этом уроке мы рассмотрим пользовательские типы записей , одну из наиболее значительных и замечательных возможностей WordPress, с помощью которой WordPress смог достичь новых высот.
Что такое пользовательские типы записей?
Предположим, вы хотите чтобы в вашем блоге был отдельный раздел для кинообзоров. Используя пользовательские типы записей вы сможете создать новый тип, к примеру, Записи и Страницы, который будет содержать другой вид данных. У него будет свое меню администратора, специальные страницы для редактирования, свои таксономии и многие другие инструменты, которые нужны для полноценной работы с публикациями.
Пользовательские типы записей - это дополнительный набор настроек администратора, который существует наряду с настройками для таких типов записей по умолчанию, как записи , страницы , прикрепленные файлы , и т.д. Пользовательские типы записей могут хранить любой тип данных. У них есть отдельный редактор, загрузчик медиафайлов, и они используют уже существующую структуру таблиц WordPress, что упрощает управление данными. Основное преимущество пользовательских типов записей, созданных при помощи WordPress API, состоит в их совместимости с уже существующими темами и шаблонами. Также, благодаря использованию постоянных ссылок, пользовательские типы постов хорошо взаимодействуют и с поисковыми системами.
Зачем использовать пользовательские типы записей?
Пользовательские типы записей помогают хранить разные типы записей в разных местах. Это помогает отделить обычные посты от других. Вот и все.
Создаем плагин для пользовательского типа записи
Мы создадим плагин для пользовательского типа записи, который будет выводить лучшие кинообзоры. Начнем.
Шаг 1 . Создайте папку для WordPress плагина
Откройте папку с WordPress плагинами и создайте новую папку Movie-Reviews .
Шаг 2 : Создайте PHP файл
В созданной папке создайте PHP файл Movie-Reviews.php
Шаг 3 : Добавьте шапку
Откройте созданный файл и вставьте код для шапки сверху.
Перед тегом закрытия PHP команды введите следующую строку кода create_movie_review . При инициализации она будет запускать соответствующую пользовательскую функцию каждый раз при генерации страницы.
Add_action("init", "create_movie_review");
Шаг 5 : Выполнение функции
Код для выполнения функции create_movie_review .
Function create_movie_review() { register_post_type("movie_reviews", array("labels" => array("name" => "Movie Reviews", "singular_name" => "Movie Review", "add_new" => "Add New", "add_new_item" => "Add New Movie Review", "edit" => "Edit", "edit_item" => "Edit Movie Review", "new_item" => "New Movie Review", "view" => "View", "view_item" => "View Movie Review", "search_items" => "Search Movie Reviews", "not_found" => "No Movie Reviews found", "not_found_in_trash" => "No Movie Reviews found in Trash", "parent" => "Parent Movie Review"), "public" => true, "menu_position" => 15, "supports" => array("title", "editor", "comments", "thumbnail", "custom-fields"), "taxonomies" => array(""), "menu_icon" => plugins_url("images/image.png", __FILE__), "has_archive" => true)); }
Функция register_post_type сделает бОльшую часть работы в нашем случае. Сразу как она вызовется, она подготовит необходимую для нового пользовательского поста конфигурацию WordPress, включая дополнительные разделы для администратора. В функцию передается два типа аргументов: уникальное имя (name) пользовательского типа поста и массив с его свойствами. Это другой массив с другими метками, которые указывают какие текстовые строки будут показываться в разных частях пользовательского типа записи, например: " name " выводит название пользовательского типа записи на панели управления, " edit " и " view " выводят кнопки Edit и View . Думаю, все остальные аргументы говорят сами за себя.
Так, в следующих аргументах:
- "public" => true задает видимость пользовательского типа записи как на панели управления администратора, так и в клиентской части.
- "menu_position" => 15 задает, где в меню, будет находиться пользовательский тип записи.
- "supports" => array("title", "editor", "comments", "thumbnail", "custom-fields") задает те атрибуты пользовательского типа записи, которые будут отображаться.
- "taxonomies" => array("") создает пользовательские таксономии. В данном случае они не определены.
- "menu_icon" => plugins_url("images/image.png", __FILE__) показывает иконку в меню администратора.
- "has_archive" => true разрешает архивирование пользовательских типов записей.
Вы можете узнать больше о других аргументах, используемых в пользовательских типах записей на странице WordPress Codex register_post_type .
Шаг 6 : Иконка для пользовательского типа записей
Сохраните иконку размером 16x16 пикселей в вашей папке с плагином. Это нужно для того, чтобы на панели управления у пользовательского типа записи была иконка.
Шаг 7 : Активируйте плагин
Активируйте плагин, и вуаля, у вас есть пользовательский тип записи с возможностью редактировать текст, настройками для публикации, изображений, комментариев, а также редактор пользовательских полей.
Шаг 8 : Добавляем новую запись
Выберите Добавить новую , чтобы открыть панель редактирования пользовательского типа записи. Добавьте название фильма, текст обзора, а также выберите миниатюру изображения.
Шаг 9 : Публикуем
Опубликуйте запись и нажмите View Movie Review , чтобы увидеть созданный кинообзор.
Создание дополнительных полей для пользовательских типов записей
Механизм дополнительных полей (метабоксов) использует встроенную в WordPress систему дополнительных полей. Это помогает добавлять поля, предназначенные исключительно для пользовательских типов записей, не используя в редакторе пользовательских полей по умолчанию.
Шаг 1 : Регистрируем пользовательскую функцию
Откройте файл Movie-Reviews.php и добавьте следующий код перед тегом закрытия. Этот код регистрирует функцию, которая будет вызываться при посещении панели администратора WordPress.
Add_action("admin_init", "my_admin");
Шаг 2 : Выполняем пользовательскую функцию
Добавьте выполнение функции my_admin , которая регистрирует дополнительные поля и связывает их с пользовательским типом записи movie_reviews .
Function my_admin() { add_meta_box("movie_review_meta_box", "Movie Review Details", "display_movie_review_meta_box", "movie_reviews", "normal", "high"); }
В данном случае функция add_meta_box используется для добавления дополнительных полей к пользовательскому типу записей. Об атрибутах:
- movie_review_meta_box необходимый атрибут для HTML id
- Movie Review Details текст, которые будет виден в заголовке дополнительного поля
- display_movie_review_meta_box функция обратного вызова которая отображает содержимое дополнительных полей
- movie_review имя пользовательского типа записи, где будут отображаться дополнительные поля
- normal определяет где на странице будет показан блок редактирования
- high определяет приоритет отображаемых полей
Шаг 3: Выполняем функцию display_movie_review_meta_box
ID, "movie_director", true)); $movie_rating = intval(get_post_meta($movie_review->ID, "movie_rating", true)); ?>Movie Director | |
Movie Rating |
Этот код выводит содержимое дополнительных полей. Здесь используется объектная переменная, которая содержит информацию о каждом из показанных на панели редактирования кинообзоров. Используя этот объект мы получили ID записи и использовали его, чтобы сделать запрос в базу данных для получения имени режиссера и рейтинга, что в свою очередь выведется в полях на экране. При добавлении новой записи, функция get_post_meta возвратит пустую строку, и в итоге дополнительные поля будут пустыми.
Шаг 4 : Регистрируем функцию сохранения записи
add_action("save_post", "add_movie_review_fields", 10, 2);Эта функция вызывается при сохранении записи в базе данных.
Шаг 5 : Выполняем функцию add_movie_review_fields
function add_movie_review_fields($movie_review_id, $movie_review) { // Check post type for movie reviews if ($movie_review->post_type == "movie_reviews") { // Store data in post meta table if present in post data if (isset($_POST["movie_review_director_name"]) && $_POST["movie_review_director_name"] != "") { update_post_meta($movie_review_id, "movie_director", $_POST["movie_review_director_name"]); } if (isset($_POST["movie_review_rating"]) && $_POST["movie_review_rating"] != "") { update_post_meta($movie_review_id, "movie_rating", $_POST["movie_review_rating"]); } } }Эта функция выполняется когда записи сохраняются или удаляются в панели администратора. В данном случае, тип получаемой записи проверяется, и, в том случае, если запись является пользовательской, вновь проводится проверка, есть ли у дополнительных полей какие-либо значения, и далее эти значения в этих полях сохраняются.
Шаг 6 : Отключаем стандартные пользовательские поля
Создавая пользовательский тип записи, мы задали функцию create_movie_review . Удалите элемент custom-fields из массива supports , поскольку он нам больше не понадобиться. Теперь, если вы сохраните файл и откроете панель редактирования Movie Reviews , вы увидите два поля в дополнительных полях: Movie Author и Movie Rating . Вы можете добавить другие элементы тем же способом.
Создание шаблона для пользовательского типа записи
Правильным будет для каждого типа пользовательских записей использовать свои шаблоны для отображения данных. В нашем случае мы создадим шаблон, которые выводит все кинообзоры, которые были добавлены с использованием пользовательского типа записи Movie Review .
Шаг 1 : Регистрируем функцию запуска шаблона
Откройте файл Movie-Reviews.php и перед тегом закрытия добавьте следующий код. Этот код регистрирует функцию, которая будет вызываться при посещении панели администратора WordPress.
Add_filter("template_include", "include_template_function", 1);
Шаг 2 : Выполняем функцию
function include_template_function($template_path) { if (get_post_type() == "movie_reviews") { if (is_single()) { // checks if the file exists in the theme first, // otherwise serve the file from the plugin if ($theme_file = locate_template(array ("single-movie_reviews.php"))) { $template_path = $theme_file; } else { $template_path = plugin_dir_path(__FILE__) . "/single-movie_reviews.php"; } } } return $template_path; }Здесь проверяется, есть ли в текущей папке темы шаблон типа single-(post-type-name).php . Если его там нет, то проверяется наличие шаблона в папке с плагином, куда мы и поместим наш шаблон, как часть плагина. Событийный обработчик (хук) template_include используется, чтобы изменить обычное выполнение программы и принудительно запустить специальный шаблон.
Шаг 3 : Создаем файл шаблона Single Page
Сохранив ранее открытый файл с плагином, создайте другой файл с именем single-movie_reviews.php и вставьте в него следующий код.
Director:
Rating: "; } else { echo ""; } } ?>
В данном случае мы создали базовый шаблон страницы с использованием цикла. Функция query_posts получает элементы пользовательского типа записей и отображает их используя цикличность. Это конечно совсем простой цикл, вы можете менять его, как вам необходимо. Вы также можете использовать необходимые CSS стили, чтобы поменять внешнее оформление.
Внимание : необходимо создать новую страницу из панели управления используя созданный шаблон.
Шаг 4: Изображения
Сохраните два изображения с иконками для звездочек размером 32x32 пикселя в вашу папку с плагином. Назовите их соответственно icon.png и grey.png . Вот и все, теперь кинообзоры показываются на отдельной странице и отсортированы по дате.
Get a valuable feedback from your customers by giving them the freedom to share their impressions freely. Let them rate your products and/or services straight on your website. See below the key features that come standard with our online review system.
Reviews & Ratings
Embed PHP Review Script into your website and let clients share their experience with the products and services you offer. They can rate by criteria and give both positive and negative feedback.
Multiple Languages
The PHP review system can speak not only English, but any language you may need. You can translate all titles and system messages from the admin page using unique IDs for each piece of text.
Editable Rating Criteria
Depending on the type of business, review system admins can
set different rating criteria to be shown in the front-end form.
Each of these criteria is rated with 1 to 5 stars.
Email & SMS Notifications
Set up the online review system to send Email & SMS alerts when a new review has been posted. You can easily specify which users to receive these messages from the Users menu.
Multiple User Types
Create unlimited client types depending on the industry and services used. Hotel ratings can go with following user types: Family with kids, Couple, Business trip etc. They appear as labels in the reviews.
Responsive & Attractive
The review and rating script runs on all devices, seamlessly adapting to various screen sizes. In accord with your website branding, you can pick the best matching front-end theme among 10 color options.
A quick tips box next to the review form allows you to add some witty words and draw customers out. The review system filters reviews by user type. Customers can rate other clients" ratings, too.
With a Developer Licence you get the source code and can make any custom changes to the PHP Review Script. We can also modify the customer review system upon request.