Красный 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
First, from a code organization standpoint, it’d be better to put all of the review logic into one or more includable files and then include it on product pages:
Include("includes/reviews.php");
This way, the product pages can remain unadulterated and the same review code can easily be used, or modified, as needed. The reviews.php script would do several things:
- Show the review form
- Handle the review form
- List the existing reviews
- Handle secondary actions, such as flagging reviews or comments as inappropriate, indicating that reviews were helpful, adding comments to reviews, indicating that comments where helpful, and so forth
Hopefully you’ve done plenty of web development already, so you know that a form for adding reviews would just be like so:
Clearly you’d want to use some CSS to make it pretty, but that’s the basic idea. The main catch is that the product ID and product type (or whatever the database must have in order to associate a review with an item) must be stored in hidden inputs. You’d have the PHP script that displays the product write these values to the inputs.
If login is required, you might add (PHP) code that only shows the form to logged-in users, or prints a comment saying the user must log in to review the product. Similarly, if you have a system in place for guaranteeing a person only ever reviews a product once, you’d have PHP check for that scenario before showing this form.
The form submission could go to a new page, but then the user would need to click the Back button to return to the product page, which isn’t ideal. I would instead submit the form back to the product page. For example, on any dynamic website, the same PHP script is used to display all the content of a specific type. In my Effortless E-Commerce with PHP and MySQL book, the first example site uses the page.php script to show any page of content. The action attribute of the form would point to the same page.php . You can accomplish this by just leaving the attribute empty, or by using PHP to dynamically set the value.
If the PHP page that lists the products requires that a value identifying the product be passed in the URL, then the form would need to store that value in a hidden input as well. (That may already be the case, with the product_id input, depending upon how the site is set up.) Secondarily, the product script would also need to be updated to allow for the product value to be received via POST .
For the reviews.php script to know when to handle a form submission, it can check how the script was accessed:
If ($_SERVER["REQUEST_METHOD"] == "POST") { // Handle the form.
When the review form is submitted, the form data should be validated. You should also apply strip_tags() to the data to prevent Cross-Site Scripting (XSS) attacks or other bad behavior. And non-numeric values would be run through an escaping function, such as mysqli_real_escape_string() . Or you could just use prepared statements or stored procedures for better security and performance.
If you add an anchor to the form’s action attribute action="page.php#reviews "the user will be taken to the reviews section of the page upon the submission, which is a nice touch.
If the reviews.php script is also handling some of the other actionsinappropriate reviews or comments, helpful indicators, etc.the script would need to watch for those submissions, too. I would use hidden inputs named “task” to indicate which action is being taken.
In a separate article, I demonstrate how to use Ajax for a simple rating system. Similar Ajax code could be used for the review system, too.
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 . Вот и все, теперь кинообзоры показываются на отдельной странице и отсортированы по дате.
A full stack framework that is faster than most if not all micro frameworks. This framework is not for beginners. It gives you the tools, but it"s up to the developer to implement them. If you have a genuine understanding of PHP, and performance is of concern, look no further. The documentation is thorough, but not beginner oriented, and the community is somewhat sparse, but I can"t stress performance enough. This framework puts my PHP applications on a performance level with JAVA applications.
Phlacon is from my point of view not just fastest framework on the market, but also it offers various features and nice components. Also very good to use as MicroFramework for restfull API"s or full MVC framework. Comes with C ORM, and twig template engine. Also what I really appreciate is how the framework is dynamic, you use only what you want, you can simply replace classes and libraries for custom ones or affect flow with events.
Very good job, only one problem is the community but I believe it will grow very fast:)
Phalcon is undoubtedly one of the most fast frameworks out there, and that"s its strong point. On the other hand, the documentation is a bit disorganized, Web tools (code generator) has major issues in Windows, and it is still lacking a bit more of a community to help new developers. But once again, performance, WOW.
Однажды Вы решили создать свой сайт или блог, а для системы управления Вы выбрали WordPress…Прошло время ваш сайт становится все более и более читаемым и тут, вы поняли, что для ещё большей популярности необходимо добавить немного функционала к сайту или же просто автоматизировать какое-то действие.
Вы идете на «склад» плагинов для wordpress и обнаруживаете, что необходимого плагина для Вас нету. Что же делать? Как быть? Если вы хотя бы немного знакомы с азами программирования на php, верстке, то Вам не составит труда Самому написать плагин для WordPress .
А теперь отправимся на «кухню» для приготовления нашего плагина.
P.s. Если знаний в php и верстке нету… не расстраивайтесь, попросите кого-либо написать Вам нужный функционал 🙂
Прежде чем начать писать плагин необходимо обратится в документацию WordPress где описаны основные принципы написания плагинов и некоторые примеры кода.
Я не буду дублировать эту информацию, а сразу перейду непосредственно к написанию кода.
Напишем простенький плагин, который позволит сохранять и выводить отзывы о Вашем сайте. Конечно, такие плагины уже есть, но для примера сойдет как раз.
Первое, что мы сделаем, это придумаем уникальное название нашему плагину - «AdvUserReviews «.
Далее создадим в директории Вашего сайта «/wp-content/plugins/» новую директорию «advuserreviews». И в ней создадим файл «advuserreviews.php». Это будет основной файл, который будет отвечать за общею инициализацию. (Желательно используйте кодировку для файлов UTF-8).
В самом начале файла необходимо указать основную информацию о плагине
Теперь, если перейти в панель управления, то можно увидеть, что система нашла новый плагин и предлагает его активировать. Но пока что это делать рано.
Наш новый плагин мы будем писать в стиле ООП и вся обработка данных будет находится в одном файле. Создадим основной каркас файла.
// Stop direct call if(preg_match("#" . basename(__FILE__) . "#", $_SERVER["PHP_SELF"])) { die("You are not allowed to call this page directly."); } if (!class_exists("AdvUserReviews")) { class AdvUserReviews { // Хранение внутренних данных public $data = array(); // Конструктор объекта // Инициализация основных переменных function AdvUserReviews() { } } } global $rprice; $rprice = new AdvUserReviews();
Теперь конструктор объекта дополним следующим кодом:
Function AdvUserReviews() { global $wpdb; // Объявляем константу инициализации нашего плагина DEFINE("AdvUserReviews", true); // Название файла нашего плагина $this->plugin_name = plugin_basename(__FILE__); // URL адрес для нашего плагина $this->plugin_url = trailingslashit(WP_PLUGIN_URL."/".dirname(plugin_basename(__FILE__))); // Таблица для хранения наших отзывов // обязательно должна быть глобально объявлена перменная $wpdb $this->tbl_adv_reviews = $wpdb->prefix . "adv_reviews"; // Функция которая исполняется при активации плагина register_activation_hook($this->plugin_name, array(&$this, "activate")); // Функция которая исполняется при деактивации плагина register_deactivation_hook($this->plugin_name, array(&$this, "deactivate")); // Функция которая исполняется удалении плагина register_uninstall_hook($this->plugin_name, array(&$this, "uninstall")); }
В конструкторе объекта мы используем 3 «хука» или «зацепки» (что это?): register_activation_hook , register_deactivation_hook и register_uninstall_hook - это функции, которые выполняются при активации, деактивации плагина и его удаления соответственно.
Теперь непосредственно реализуем эти функции.
/** * Активация плагина */ function activate() { global $wpdb; require_once(ABSPATH . "wp-admin/upgrade-functions.php"); $table = $this->tbl_adv_reviews; // Определение версии mysql if (version_compare(mysql_get_server_info(), "4.1.0", ">=")) { if (! empty($wpdb->charset)) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; if (! empty($wpdb->collate)) $charset_collate .= " COLLATE $wpdb->collate"; } // Структура нашей таблицы для отзывов $sql_table_adv_reviews = " CREATE TABLE `".$wpdb->prefix."adv_reviews` (`ID` INT(10) UNSIGNED NULL AUTO_INCREMENT, `review_title` VARCHAR(255) NOT NULL DEFAULT "0", `review_text` TEXT NOT NULL, `review_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `review_user_name` VARCHAR(200) NULL, `review_user_email` VARCHAR(200) NULL, PRIMARY KEY (`ID`))".$charset_collate.";"; // Проверка на существование таблицы if ($wpdb->get_var("show tables like "".$table.""") != $table) { dbDelta($sql_table_adv_reviews); } } /** * Деактивация плагина */ function deactivate() { return true; } /** * Удаление плагина */ function uninstall() { global $wpdb; $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}adv_reviews"); }
Переменная $wpdb отвечает за запросы к базе Данных. Функция dbDelta анализирует текущую структуру таблицы, сравнивает ee с желаемой структурой таблицы, и либо добавляет или изменяет таблицу по мере необходимости.
Соответственно, при активации плагина создается структура таблицы для хранения отзывов. При деактивации плагина не происходит никаких действий, а вот при удалении мы удаляем нашу таблицу. Более подробно действия можно понять по исходному коду.
Основная структура нового плагина готова. Теперь необходимо приступить к написанию функциональной части. Для этого в конструктор класса нам необходимо добавить следующие строчки кода:
// Если мы в адм. интерфейсе if (is_admin()) { // Добавляем стили и скрипты add_action("wp_print_scripts", array(&$this, "admin_load_scripts")); add_action("wp_print_styles", array(&$this, "admin_load_styles")); // Добавляем меню для плагина add_action("admin_menu", array(&$this, "admin_generate_menu")); } else { // Добавляем стили и скрипты add_action("wp_print_scripts", array(&$this, "site_load_scripts")); add_action("wp_print_styles", array(&$this, "site_load_styles")); add_shortcode("show_reviews", array (&$this, "site_show_reviews")); }
Разберем подробнее данный участок кода. Начнем с панели администрирования.
Функция «is_admin
» проверяет в каком режиме сейчас мы работаем - на сайте или в панель управления.
Далее используется несколько хуков, для функций:
- wp_print_scripts - Добавляем необходимые javascript файлы
- wp_print_styles - Добавляем необходимые стили
- admin_menu - Добавляем новое меню в панели управления
Каждому хуку соответствует реализованный метод в нашем классе. В котором выполняются необходимые операции.
Рассмотрим код для подключения стилей и скриптов
/** * Загрузка необходимых скриптов для страницы управления * в панели администрирования */ function admin_load_scripts() { // Регистрируем скрипты wp_register_script("advReviewsAdminJs", $this->plugin_url . "js/admin-scripts.js"); wp_register_script("jquery", $this->plugin_url . "js/jquery-1.4.2.min.js"); // Добавляем скрипты на страницу wp_enqueue_script("advReviewsAdminJs"); wp_enqueue_script("jquery"); } /** * Загрузка необходимых стилей для страницы управления * в панели администрирования */ function admin_load_styles() { // Регистрируем стили wp_register_style("advReviewsAdminCss", $this->plugin_url . "css/admin-style.css"); // Добавляем стили wp_enqueue_style("advReviewsAdminCss"); }
Здесь используются следующие функции.
Каждое действие зависит от переданного параметра «action», соответственно «edit» -редактирование отзыва, «submit» - сохранение отредактированного отзыва и «delete» - удаление отзыва.
Обмен данными со страницами отображения происходит через свойство объекта «data». Исходный код этих страниц будет выложен в архиве с данным модулем в конце статьи. Тут я их не буду вставлять, так как топик уже оказался достаточно большим.
На этом с панелью администрирования заканчиваем и переходит к отображению и добавлению отзывов со стороны пользователей.
Что бы указать wordpress, когда вызывать наш плагин, необходимо зарегистрировать «shortcode», что и было сделано в конструкторе нашего класса. Подробнее об этом .
Add_shortcode("show_reviews", array (&$this, "site_show_reviews"));
Теперь на любой странице сайта можно разместить вот такой код и это заставит выполнить указанную нами функцию (передается вторым параметром). Ниже представлен исходный код данной функции.
/** * Список отзывов на сайте */ public function site_show_reviews($atts, $content=null) { global $wpdb; if (isset($_POST["action"]) && $_POST["action"] == "add-review") { $this->add_user_review(); } // Выбираем все отзывы из Базы Данных $this->data["reviews"] = $wpdb->get_results("SELECT * FROM `" . $this->tbl_adv_reviews . "`", ARRAY_A); ## Включаем буферизацию вывода ob_start (); include_once("site_reviews.php"); ## Получаем данные $output = ob_get_contents (); ## Отключаем буферизацию ob_end_clean (); return $output; } private function add_user_review() { global $wpdb; $inputData = array("review_title" => strip_tags($_POST["review_title"]), "review_text" => strip_tags($_POST["review_text"]), "review_user_name" => strip_tags($_POST["review_user_name"]), "review_user_email" => strip_tags($_POST["review_user_email"]),); // Добавляем новый отзыв на сайт $wpdb->insert($this->tbl_adv_reviews, $inputData); }
В принципе тут ничего сложного нету - делается SQL запрос на выборку данных, если же передан параметр «action», то сначала добавляется новый отзыв. Но стоит обратить внимание на буферизацию вывода. Она необходима для того, что бы получить данные вставляемой страницы.
Вот собственно и все. Теперь можно посмотреть, что у нас получилось. А скачать плагин и исходные коды можно вот .
Само собой это только пример создания плагина, но и сойдет как простая гостевушка, если ее немного доработать, например, добавить защиту от ботов и постраничный вывод. Удачного кодинга:)
Форма на сайте:
Панель управления плагином:
Редактирование отзыва: